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 0s. If the number is zero, it's represented by a single zero character' 0 'Otherwise, the first character in the hexadecimal string would not be the zero character. The given number is guaranteed to fit within the range of a32-bit signed integer. You must don't use any method provided by the library which converts/Formats the number to hex directly. Example1: Input:26Output:"1a"Example2: Input:-1Output:"FFFFFFFF"
Remember to delete begining 0
1 Public classSolution {2 PublicString Tohex (intnum) {3StringBuffer res =NewStringBuffer ();4string[] Charmap =Newstring[]{"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "B", "C", "D", "E", "F"};5 for(inti=0; i<8; i++) {6 intNumber = num &(0b1111);7num = num >>> 4;8Res.insert (0, Charmap[number]);9 }Ten while(Res.charat (0) = = ' 0 ' && res.length () >1) Res.deletecharat (0); One returnres.tostring (); A } -}
Remember to handle num = = 0 alone
1 Public classSolution {2 PublicString Tohex (intnum) {3 if(num = = 0)return"0";4StringBuffer res =NewStringBuffer ();5string[] Charmap =Newstring[]{"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "B", "C", "D", "E", "F"};6 while(num! = 0) {7 intNumber = num &(0b1111);8num = num >>> 4;9Res.insert (0, Charmap[number]);Ten } One returnres.tostring (); A } -}
Leetcode:convert a number to hexadecimal