美文网首页
405. 数字转换为十六进制数-leetcode

405. 数字转换为十六进制数-leetcode

作者: 佛祖拿屠刀 | 来源:发表于2018-12-26 23:37 被阅读0次

给定一个整数,编写一个算法将这个数转换为十六进制数。对于负整数,我们通常使用 补码运算 方法。

注意:

十六进制中所有字母(a-f)都必须是小写。
十六进制字符串中不能包含多余的前导零。如果要转化的数为0,那么以单个字符'0'来表示;对于其他情况,十六进制字符串中的第一个字符将不会是0字符。
给定的数确保在32位有符号整数范围内。
不能使用任何由库提供的将数字直接转换或格式化为十六进制的方法。
示例 1:

输入:
26

输出:
"1a"

示例 2:

输入:
-1

输出:
"ffffffff"

这个题目无非就是一直取与,移位

temp & 0xf
temp = temp >> 4

但是swift有点肯定,负数不能移位

所以只能换个办法,移动取与的数

(temp & (0xf << count)) >> count
count = count + 4

然后写代码

class Solution {
    func toHex(_ num: Int) -> String {
        if num < 16 && num > -1 {
            return toString(num)
        }
        var res = ""

        var temp = num
        var count = 0
        while temp != 0 && count < 32{
            if temp < 0 {
                let str = toString((temp & (0xf << count)) >> count)
                count = count + 4
                res = str + res
            } else{
                let str = toString(temp & 0xf) 
                temp = temp >> 4
                res = str + res
            }
        }
        
        return res
    }
    
    func toString(_ num:Int) ->String {
        switch num {
            case 10:return "a"
            case 11:return "b"
            case 12:return "c"
            case 13:return "d"
            case 14:return "e"
            case 15:return "f"
            default:break
        }
        return "\(num)"
    }
}

相关文章

网友评论

      本文标题:405. 数字转换为十六进制数-leetcode

      本文链接:https://www.haomeiwen.com/subject/btrllqtx.html