的Codility問題和測試用例示於:here爲什麼代碼在Codility測試用例中返回負值?
寫入golang的代碼:
func Solution(A []int, B []int) []int {
result := make([]int, len(A))
step := make([]int, len(A)+1)
step[0] = 1
step[1] = 1
for i := 2; i <= len(A); i++ {
step[i] = step[i-1] + step[i-2]
}
for i := 0; i < len(A); i++ {
result[i] = int(int32(step[A[i]]) % int32(math.Pow(2, float64(B[i]))))
// result[i] = step[A[i]] & (1<<uint(B[i]) - 1)
}
return result
}
的result[i] = step[A[i]] & (1<<uint(B[i]) - 1)
通過了所有病例。但result[i] = int(int32(step[A[i]]) % int32(math.Pow(2, float64(B[i]))))
或result[i] = step[A[i]] % int(math.Pow(2, float64(B[i])))
產生一些負數。
看起來有些東西溢出。有人會知道原因嗎?謝謝!
您是否使用了與您提供的鏈接中給定的A和B完全相同的數組?如果A和B都由小的正整數組成,我看不到結果爲負的任何理由。 –
示例數組結果OK。但是在提交代碼後,它在某些情況下失敗了。不幸的是,codilty並沒有顯示完全的測試用例,所以我不知道在這種情況下使用的數組。奇怪! – victor1ee