You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
lavos/cap3/work1.go

28 lines
1.1 KiB

package cap3
// Work1 求 2 + 22 + 222 + 2222 + ...22...22(n个2)的精确值,返回大端序结果,高位在前存放结果
// 按位直接计算结果,从最低位(结果索引的末尾)开始,
// 每一位(索引i)的计算结果为2*(i+1)加上进位,该位的数字即为结果%10,进位即为结果/10取整。
// 如n=10,则最低位(i=9)的计算结果为(9+1)*2 + 0 = 20,该位数字为result[i]=20%10=0,进位carry=20/10=2,
// 下一位(i=8)计算结果为(8+1)*2 + 2 = 20,该位数字为result[i]=20%10=0,进位carry=20/10=2,
// 下一位(i=7)计算结果为(7+1)*2 + 2 = 18,该位数字为result[i]=18%10=8,进位carry=18/10=1,
// 以此类推
func Work1(n int) []uint8 {
// 大端序,高位在前存放结果
result := make([]uint8, n)
carry := 0
for i := n - 1; i >= 0; i-- {
num := (i+1)*2 + carry
carry = num / 10
result[i] = uint8(num % 10)
}
if carry != 0 {
result = append(result, 0)
copy(result[1:], result[0:])
result[0] = uint8(carry)
}
return result
}