Given a non-negative integer c
, your task is to decide whether there're two integers a
and b
such that a2 + b2 = c.
Example 1:
Input: 5
Output: True
Explanation: 1 * 1 + 2 * 2 = 5
Example 2:
Input: 3
Output: False
题意:
给定非负整数c,问是否存在整数a、b,使得 a2 + b2 = c
code
1 class Solution { 2 public boolean judgeSquareSum(int c) { 3 if (c < 0) { 4 return false; 5 } 6 int left = 0, right = (int)Math.sqrt(c); 7 while (left <= right) { 8 int cur = left * left + right * right; 9 if (cur < c) { 10 left++; 11 } else if (cur > c) { 12 right--; 13 } else { 14 return true; 15 } 16 } 17 return false; 18 } 19 }