-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathconvert_a_number_to_hexadecimal.dart
71 lines (47 loc) · 1.23 KB
/
convert_a_number_to_hexadecimal.dart
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
/*
-* 405. Convert a Number to Hexadecimal *-
Given an integer num, return a string representing its hexadecimal representation. For negative integers, two’s complement method is used.
All the letters in the answer string should be lowercase characters, and there should not be any leading zeros in the answer except for the zero itself.
Note: You are not allowed to use any built-in library method to directly solve this problem.
Example 1:
Input: num = 26
Output: "1a"
Example 2:
Input: num = -1
Output: "ffffffff"
Constraints:
-231 <= num <= 231 - 1
*/
String toHexString(int num) {
if (num == 0) {
return "0";
}
int n = num.toUnsigned(32);
final String ref = "0123456789abcdef";
String result = "";
while (n != 0) {
result = ref[n & 0xF] + result;
n >>= 4;
}
return result;
}
String toHex(int num) {
return (num < 0)
? (num.toUnsigned(32)).toRadixString(16)
: num.toRadixString(16);
}
extension ToHex on int {
String toHexString(int num) {
if (num == 0) {
return "0";
}
int n = num.toUnsigned(32);
final String ref = "0123456789abcdef";
String result = "";
while (n != 0) {
result = ref[n & 0xF] + result;
n >>= 4;
}
return result;
}
}