[LeetCode By Go 64]405. Convert a Number to Hexadecimal

题目

Given an integer, write an algorithm to convert it to hexadecimal. For negative integer, two’s complement method is used.
Note:

  1. All letters in hexadecimal (a-f) must be in lowercase.
  2. 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.
  3. The given number is guaranteed to fit within the range of a 32-bit signed integer.
  4. You must not use any method provided by the library which converts/formats the number to hex directly.

Example 1:

Input:26
Output:"1a"

Example 2:

Input:-1
Output:"ffffffff"

解题思路

  1. 如果是0,则直接返回
  2. 如果是负数,则用232 + num得到负数的补码并求16进制值
  3. 如果是正整数,则循环整除,得到16进制数的每一位

代码

toHex.go

package _405_Convert_a_Number2Hexadecimal

import "strconv"

func getHexDigit(a int) (hex string){
    if a < 10 {
        return strconv.Itoa(a)
    }

    return string([]byte{'a' + byte(a - 10)})
}
func ToHex(num int) string {
    if 0 == num {
        return "0"
    } else if num < 0 {
        num = 4294967296 + num
    }

    var ret string
    for ; num > 0; {
        a := num % 16
        num = num / 16

        hexDigit := getHexDigit(a)
        ret = hexDigit + ret
    }

    return ret
}

测试

toHex_test.go

package _405_Convert_a_Number2Hexadecimal

import "testing"

func TestToHex(t *testing.T) {
    var tests = []struct{
        num int
        out string
    }{
        {0, "0"},
        {26, "1a"},
        {-1, "ffffffff"},
    }

    for _, v := range tests {
        ret := ToHex(v.num)

        if ret == v.out {
            t.Logf("pass")
        } else {
            t.Errorf("fail, want %+v,  get %+v\n", v.out, ret)
        }
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

友情链接更多精彩内容