您的位置:首页 > 其它

Leetcode 405 Convert a Number to Hexadecimal

2016-10-29 14:54 302 查看
Given an integer, write an algorithm to convert it to hexadecimal. For negative integer, two’s
complementmethod is used.

Note:
All letters in hexadecimal (
a-f
) must be in lowercase.
The hexadecimal string must not contain extra leading 
0
s. 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.
public class Solution {
public String toHex(int num) {
String hex = "";
int Num = num;//防止操作改变num的值 复制一遍
if(Num == 0)
hex = hex + Integer.toString(0);
if(num < 0)
Num = (Num + 2147483647) + 1;  //注意负数的情况 比如 ffffffff(signed) = 2的31次方减一 所以对-1 应该加上1 再加上2的31次方减一
int time = 0;
while(Num > 0||(num<0 && time<8)){
int post = Num%16; //余数 作为当前位
Num = Num/16;//商  继续计算
if(time==7 && num<0)//如果已经有了前面七位并且输入的数字是一个负数的话 最高位第八位的第一个bit要置为1
post += 8;
if(post>=10){ //16进制的字母转换
hex = (char)('a' + (post -10))+hex;
}
else
hex = "" + Integer.toString(post) + hex;  //每次都重新整理string的内容
time++;

}
return hex;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: