[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)
        }
    }
}
    原文作者:miltonsun
    原文地址: https://www.jianshu.com/p/48ac8a6792b3
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞