diff options
author | Jack Sangdahl <[email protected]> | 2025-03-15 02:05:58 -0600 |
---|---|---|
committer | Jack Sangdahl <[email protected]> | 2025-03-15 02:05:58 -0600 |
commit | 5e923e65f2bef08dd917ca1cf9581a7a60bab8c9 (patch) | |
tree | 8b7f0c5080c8c093839c1e9b35d808287e8e7f17 /convert_num_hex.c | |
parent | 95c460fc44a3ccee0b366b67cf47df0576f2fa32 (diff) | |
download | leetcode-5e923e65f2bef08dd917ca1cf9581a7a60bab8c9.tar.gz leetcode-5e923e65f2bef08dd917ca1cf9581a7a60bab8c9.zip |
405. convert a number to hexadecimal
Diffstat (limited to 'convert_num_hex.c')
-rw-r--r-- | convert_num_hex.c | 35 |
1 files changed, 35 insertions, 0 deletions
diff --git a/convert_num_hex.c b/convert_num_hex.c new file mode 100644 index 0000000..421706b --- /dev/null +++ b/convert_num_hex.c @@ -0,0 +1,35 @@ +// 405. Convert a Number to Hexadecimal +#include "leetcode.h" + +/* + * given a 32 bit 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, nd there 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. + */ + +char *toHex(int num) { + char *ans = (char *)malloc(sizeof(char) * 10), step; + uint x = num, i = 0; + ans[9] = '\0'; + while (1) { + step = x & 0xF; + ans[8 - i] = step > 9 ? 'a' + step - 10 : '0' + step; + x >>= 4; + if (!x) + break; + i++; + } + return &ans[8 - i]; +} + +int main() { + char *th1 = toHex(26); + char *th2 = toHex(-1); + printf("%s\n", th1); // expect: 1a + printf("%s\n", th2); // expect: ffffffff + free(th1); + free(th2); +} |