题目: Given an integer, write an algorithm to convert it to hexadecimal. For negative integer, two’s complement method is used. Note:
All letters in hexadecimal (a-f) must be in lowercase.The hexadecimal string must not contain extra leading 0s. If the number is zero, it is represented by a single zero character ‘0’; otherwise, the first character in the hexadecimal string will not be the zero character.The given number is guaranteed to fit within the range of a 32-bit signed integer.You must not use any method provided by the library which converts/formats the number to hex directly.解决方法:如果单纯的推算十六进制的方法来做,需要考虑0,负数与正数的区别 但可以利用数据在计算机中的存储形式,每次读取存储的后四位,并按照0-9,a-z的形式读取即可。然后再将数据右移,重复此操作直至所有数据均读取。 public String toHex(int num) { String s=""; do{ int rem = num & 15; if(rem < 10) s=rem+s; else { s=(char)(rem-10+‘a’)+s; } num >>>= 4; }while(num!=0); return s; }