求二进制表示
package main
import (
"fmt"
"math"
)
func main(){
binStr := subtractionOfPowers(1234321)
fmt.Println(binStr)
binStr = div2(1234321)
fmt.Println(binStr)
}
func subtractionOfPowers(n int) string{
result := ""
maxN := 0
for i:=0;;i++{
if n < int(math.Pow(2.0, float64(i))) {
maxN = i
break
}
}
if maxN>1{
result = ""
}
rem:=n
for j:=maxN-1; j>0;j--{
temp := rem - int(math.Pow(2.0, float64(j)))
//fmt.Println(rem, int(math.Pow(2.0, float64(j))), temp)
if rem>=int(math.Pow(2.0, float64(j))){
result = result + "1"
rem = temp
} else {
result = result + "0"
}
//fmt.Printf("maxN=%s\n", result)
}
if n%2 == 0{
result += "0"
} else {
result += "1"
}
return result
}
func div2(x int) string{
result := ""
n := x
for {
if n%2 == 0 {
result = "0" + result
} else {
result = "1" + result
}
n = n/2
if n <= 0 {
break
}
}
return result
}
爱书网:www.2ibook.com 一个优秀的视频教学网站,大学各专业的名师课程。免费,免费,免费。
QQ群:762080163
QQ群:762080163