The original title link is here: https://leetcode.com/problems/convert-a-number-to-hexadecimal/
Topic:
Given an integer, write a algorithm to convert it to hexadecimal. For negative integer, the complement method is used.
Note:
- All letters in hexadecimal (
a-f
) must is in lowercase.
- The hexadecimal string must not contain extra leading
0
s. If the number is zero, it's represented by a single zero character ‘0‘
; otherwise, the first character in the HEXADECIM Al string would not be the zero character.
- The given number is guaranteed to fit within the range of a 32-bit signed integer.
- You must don't use any method provided by the library which converts/formats the number to hex directly.
Example 1:
Input:26output: "1a"
Example 2:
Input:-1output: "FFFFFFFF"
Exercises
Each of the 4 bits consists of a hexadecimal digit, each taking out the last 4 bits and 1111 doing bit arithmetic & getting a digit.
Num moves right 4 bits, here with >>> instead of >>. e.g.-1 of two ' s complement is represented as FFFFFFFF, 32 bits are all 1 bit. If the 1 bit with >> first does not move, the condition num!=0 of the while loop does not appear.
Time Complexity:o (1). Space:o (1).
AC Java:
1 Public classSolution {2 PublicString Tohex (intnum) {3 if(num = = 0){4 return"0";5 }6 7StringBuilder SB =NewStringBuilder ();8 while(num! = 0){9 intdigit = num & 0xf;TenSb.insert (0, digit<10?) (Char) (digit+ ' 0 '): (Char) (digit-10+ ' a ')); OneNum >>>= 4; A } - returnsb.tostring (); - } the}
Leetcode Convert a number to hexadecimal