用开方的思想来解题。
bool judgeSquareSum(int c) { int h = pow(c, 0.5); for (int i = 0; i <= h; i++) { double left = pow(c - pow(i, 2), 0.5); if (left - int(left) == 0.0) { return true; } } return false; }
补充一个phthon的实现,使用双指针思想:
1 class Solution: 2 def judgeSquareSum(self, c: int) -> bool: 3 i=0 4 j=int(c ** 0.5) 5 while i<=j: 6 target = i*i +j*j 7 if target==c: 8 return True 9 elif target>c: 10 j-=1 11 else: 12 i+=1 13 14 return False