Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 63cd7d8

Browse files
author
guangsheng.li01
committed
Solved 0405
1 parent 6f758d7 commit 63cd7d8

File tree

2 files changed

+61
-0
lines changed

2 files changed

+61
-0
lines changed
Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
/*
2+
* [0405] convert-a-number-to-hexadecimal
3+
*/
4+
5+
pub struct Solution {}
6+
7+
// solution impl starts here
8+
9+
impl Solution {
10+
pub fn to_hex(num: i32) -> String {
11+
if num == 0 {
12+
return "0".to_string();
13+
}
14+
let s = "0123456789abcdef";
15+
let m = 0x0000000f;
16+
let mut n: i64 = num as i64 & 0xffffffff;
17+
let mut r = String::new();
18+
while n > 0 {
19+
r.push(s.chars().nth((n & m) as usize).unwrap());
20+
n >>= 4;
21+
}
22+
r.chars().rev().collect::<String>()
23+
}
24+
}
25+
26+
// solution impl ends here
27+
28+
// solution tests starts here
29+
30+
#[cfg(test)]
31+
mod tests {
32+
use super::*;
33+
34+
#[test]
35+
fn test_case0() {
36+
assert_eq!(Solution::to_hex(26), "1a");
37+
}
38+
39+
#[test]
40+
fn test_case1() {
41+
assert_eq!(Solution::to_hex(-1), "ffffffff");
42+
}
43+
44+
#[test]
45+
fn test_case2() {
46+
assert_eq!(Solution::to_hex(-2), "fffffffe");
47+
}
48+
49+
#[test]
50+
fn test_case3() {
51+
assert_eq!(Solution::to_hex(0), "0");
52+
}
53+
54+
#[test]
55+
fn test_case4() {
56+
assert_eq!(Solution::to_hex(111111), "1b207");
57+
}
58+
}
59+
60+
// solution tests ends here

‎src/lib.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ mod a0145_binary_tree_postorder_traversal;
1111
mod a0172_factorial_trailing_zeroes;
1212
mod a0400_nth_digit;
1313
mod a0404_sum_of_left_leaves;
14+
mod a0405_convert_a_number_to_hexadecimal;
1415
mod a0617_merge_two_binary_trees;
1516
mod a0643_maximum_average_subarray_i;
1617
mod a0929_unique_email_addresses;

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /