1. 程式人生 > >lintcode: Check Sum of Square Numbers

lintcode: Check Sum of Square Numbers

floor data- logs footer -s div strong you cksum

Check Sum of Square Numbers

Given a integer c, your task is to decide whether there‘re two integers a and b such that a^2 + b^2 = c.

您在真實的面試中是否遇到過這個題? Yes 樣例

Given n = 5
Return true // 1 * 1 + 2 * 2 = 5

Given n = -5
Return false

代碼

 1 class Solution {
 2 public:
 3     /*
 4      * @param : the given number
5 * @return: whether whether there‘re two integers 6 */ 7 bool checkSumOfSquareNumbers(int num) { 8 // write your code here 9 if (num < 0) { 10 return false; 11 } 12 int c = floor(sqrt(num)); 13 int i = c; 14 if (i * i == num) return
true; 15 int j = 1; 16 while (j <= i) { 17 if (i * i + j * j == num) { 18 return true; 19 } else if (i * i + j * j < num) { 20 j++; 21 } else { 22 i--; 23 } 24 } 25 return
false; 26 } 27 };

lintcode: Check Sum of Square Numbers