Golang | Leetcode Golang题解之第405题数字转换为十六进制数

题目:

题解:

Go 复制代码
func toHex(num int) string {
    if num == 0 {
        return "0"
    }
    sb := &strings.Builder{}
    for i := 7; i >= 0; i-- {
        val := num >> (4 * i) & 0xf
        if val > 0 || sb.Len() > 0 {
            var digit byte
            if val < 10 {
                digit = '0' + byte(val)
            } else {
                digit = 'a' + byte(val-10)
            }
            sb.WriteByte(digit)
        }
    }
    return sb.String()
}
相关推荐
无聊的小坏坏3 小时前
拓扑排序详解:从力扣 207 题看有向图环检测
算法·leetcode·图论·拓扑学
浮灯Foden6 小时前
算法-每日一题(DAY13)两数之和
开发语言·数据结构·c++·算法·leetcode·面试·散列表
执子手 吹散苍茫茫烟波7 小时前
leetcode415. 字符串相加
java·leetcode·字符串
执子手 吹散苍茫茫烟波9 小时前
LCR 076. 数组中的第 K 个最大元素
leetcode·排序算法
山顶风景独好10 小时前
【Leetcode】随笔
数据结构·算法·leetcode
·白小白14 小时前
力扣(LeetCode) ——100. 相同的树(C语言)
c语言·算法·leetcode
墩墩同学15 小时前
【LeetCode题解】LeetCode 74. 搜索二维矩阵
算法·leetcode·二分查找
1白天的黑夜118 小时前
前缀和-560.和为k的子数组-力扣(LeetCode)
c++·leetcode·前缀和
m0_6728137718 小时前
Leetcode-3427变长子数组求和
leetcode
崎岖Qiu18 小时前
leetcode100.相同的树(递归练习题)
算法·leetcode·二叉树·力扣·递归