classSolution{ publicbooleanjudgeSquareSum(int c){ int a = 0, b = (int) Math.sqrt(c); while (a <= b) { if (a*a + b*b == c) { returntrue; } elseif (a*a + b*b < c) { a++; } else { b--; } } returnfalse; } }
解决方案是2(Golang)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
func judgeSquareSum(c int) bool { left, right := 0, int(math.Sqrt(float64(c))) for left <= right { sum := left * left + right * right if sum == c { return true } else if sum > c { right-- } else { left++ } } return false }