File tree 2 files changed +71
-0
lines changed
2 files changed +71
-0
lines changed Original file line number Diff line number Diff line change
1
+ import java .util .*;
2
+
3
+ /** 如果有多种方法, 可以将文件名和class 名字都改为 Leetcode1_method2或Leetcode1b 这种格式 */
4
+ class Leetcode405a {
5
+ public String toHex (int num ) {
6
+ String res = "" ;
7
+ long N = num ; // 预处理
8
+ if (N == 0 )
9
+ return "0" ;
10
+ HashMap <Integer , Character > dict = new HashMap <Integer , Character >() {
11
+ {
12
+ put (0 , '0' );
13
+ put (1 , '1' );
14
+ put (2 , '2' );
15
+ put (3 , '3' );
16
+ put (4 , '4' );
17
+ put (5 , '5' );
18
+ put (6 , '6' );
19
+ put (7 , '7' );
20
+ put (8 , '8' );
21
+ put (9 , '9' );
22
+ put (10 , 'a' );
23
+ put (11 , 'b' );
24
+ put (12 , 'c' );
25
+ put (13 , 'd' );
26
+ put (14 , 'e' );
27
+ put (15 , 'f' );
28
+ }
29
+ };
30
+ if (N < 0 ) N = 4294967296L + N ; /* 4294967296L就是 0x0000000100000000(16^8=2^32), Java中
31
+ * 不使用BigInteger无法存储该数, 只能hard code在这里了
32
+ */
33
+ while (N > 0 ) {
34
+ long lastDigit = N % 16 ;
35
+ N /= 16 ;
36
+ res = dict .get ((int ) lastDigit ) + res ;
37
+ }
38
+ return res ;
39
+ }
40
+
41
+ public static void main (String [] args ) {
42
+ Leetcode405a sol = new Leetcode405a ();
43
+ int num = 7 ;
44
+ String res = sol .toHex (num );
45
+ System .out .println (res );
46
+ }
47
+ }
Original file line number Diff line number Diff line change
1
+ /** 如果有多种方法, 可以将文件名和class 名字都改为 Leetcode1_method2或Leetcode1b 这种格式 */
2
+ class Leetcode405b {
3
+ public String toHex (int num ) {
4
+ String res = "" ;
5
+ long N = num ; // 预处理
6
+ if (N == 0 ) return "0" ;
7
+ String dict = "0123456789abcdef" ;
8
+ if (N < 0 ) N = 4294967296L + N ; /* 4294967296L就是 0x0000000100000000(16^8=2^32), Java中不使用BigInteger无法存储, 只能hard code在这里了 */
9
+ while (N > 0 )
10
+ {
11
+ long lastDigit = N % 16 ;
12
+ N /= 16 ;
13
+ res = dict .charAt ((int )lastDigit ) + res ;
14
+ }
15
+ return res ;
16
+ }
17
+
18
+ public static void main (String [] args ) {
19
+ Leetcode405a sol = new Leetcode405a ();
20
+ int num = 7 ;
21
+ String res = sol .toHex (num );
22
+ System .out .println (res );
23
+ }
24
+ }
You can’t perform that action at this time.
0 commit comments