题目
Given an integer, return its base 7 string representation.
Example 1:
Input: 100
Output: “202”
Example 2:
Input: -7
Output: “-10”
Note: The input will be in range of [-1e7, 1e7].
解题思路
- 首先判断输入是否为负数,如果为负数,输出字符串上添加“-”,并将num取成正数
- 对正整数循环取余数,并将获得的余数放在原字符串前面
- 拼接字符串获得结果
注意
需要判断正整数是否为0,如果为零则转换为“0”
代码
base7.go
package _504_Base7
import "strconv"
func ConvertToBase7(num int) string {
var ret string
if num < 0 {
ret += "-"
num = -num
}
var base7 string
if 0 == num {
base7 = "0"
} else {
for ;num > 0; {
base7 = strconv.Itoa(num % 7) + base7
num = num / 7
}
}
ret += base7
return ret
}
测试
base7_test.go
package _504_Base7
import "testing"
func TestConvertToBase7(t *testing.T) {
var tests = []struct{
input int
output string
} {
{-7, "-10"},
{101, "203"},
{0, "0"},
}
for _, v := range tests {
ret := ConvertToBase7(v.input)
if ret == v.output {
t.Logf("pass")
} else {
t.Errorf("fail, want %+v, get %+v\n", v.output, ret)
}
}
}