Valid Number
题目描述
Given two binary strings, return their sum (also a binary string).
For example,
a ="11"
b ="1"
Return"100"
思路:
- 字串先对齐,再相加,再进。
细节:
- 用字节数组处理字串。
解:
package main
import "fmt"
func addBinary(a string, b string) string {
var maxLen int
switch len(a) > len(b) {
case true:
maxLen = len(a)
case false:
maxLen = len(b)
}
aByte := make([]byte,maxLen+1)
for idx,_ := range aByte {
aByte[idx] = 48
}
bByte := make([]byte,maxLen+1)
for idx,_ := range bByte{
bByte[idx] = 48
}
for i := 0; i < len(a); i++ {
aByte[i+maxLen-len(a)+1] = a[i]
}
for i := 0; i < len(b); i++ {
bByte[i+maxLen-len(b)+1] = b[i]
}
preString := make([]byte,maxLen+1)
for i := 0; i < maxLen+1; i++ {
preString[i] = aByte[i]+bByte[i]- 48
}
for i := maxLen; i > 0; i-- {
if preString[i] == 50 {
preString[i] = 48
preString[i-1] = preString[i-1]+1
}else if preString[i] == 51 {
preString[i] = 49
preString[i-1] = preString[i-1]+1
}
}
if preString[0] == 49 {
return string(preString)
}
return string(preString[1:])
}
func main() {
a := "11"
b := "1"
fmt.Print(addBinary(a,b))
}
网友评论