題目
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].
解題思路
- 首先判斷輸入是否為負(fù)數(shù),如果為負(fù)數(shù),輸出字符串上添加“-”砸西,并將num取成正數(shù)
- 對(duì)正整數(shù)循環(huán)取余數(shù)器紧,并將獲得的余數(shù)放在原字符串前面
- 拼接字符串獲得結(jié)果
注意
需要判斷正整數(shù)是否為0叠纹,如果為零則轉(zhuǎn)換為“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
}
測(cè)試
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)
}
}
}