LeetCode-Java-405. Convert a Number to Hexadecimal

53 篇文章 0 订阅
53 篇文章 0 订阅

题目

Given an integer, write an algorithm to convert it to hexadecimal. For negative integer, two’s complement method is used.
给一个数,写一个算法将其转化为16进制,对于负整数,使用二进制补码方式
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.
十六进制(a-f)中的所有字母必须为小写。
十六进制字符串不得包含额外的前导0。 如果数字为零,则由单个零字符“0”表示; 否则,十六进制字符串中的第一个字符将不是零字符。
保证给定数字适合32位有符号整数的范围。
您不得使用库提供的任何方法将数字直接转换/格式化为十六进制。
Example 1:

Input:
26

Output:
"1a"
Example 2:

Input:
-1

Output:
"ffffffff"

代码

class Solution {
    public String toHex(int num) {
        if(num==0)
            return "0";
        String[] map = {"0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f"};
        StringBuilder str = new StringBuilder();
        while(num!=0)
        {
            str.insert(0,map[(num&15)]);
            //此为无符号右移4位等于除以16
            num>>>=4;
        }
        return str.toString();
    }
}

此段代码的难点在于temp&15
其实他的含义为

15的2进制   : 1111
1 的2进制   :    1
16的2进制   :10000
17的2进制   :10001
 1&15: 1
16&15: 0
17&15: 1

可以看出15的2进制为1111任何数和它进行&运算以后都会只剩下后四位的值,而后四位2进制恰好为16进制的一位,这样每次用4位进行&运算就可以转换为16进制。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值