633. Sum of Square Numbers

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^2+b^2

C++(3ms):
 1 class Solution {
 2 public:
 3     bool judgeSquareSum(int c) {
 4         int left = 0 ;
 5         int right = (int)sqrt(c) ;
 6         while(left <= right){
 7             int cur = left*left + right*right ;
 8             if (cur == c){
 9                 return true ;
10             }else if (cur < c){
11                 left++ ;
12             }else{
13                 right-- ;
14             }
15         }
16         return false ;
17     }
18 };

 

java(14ms):

 1 class Solution {
 2     public boolean judgeSquareSum(int c) {
 3         int left = 0 ;
 4         int right = (int)Math.sqrt(c) ;
 5         while(left <= right){
 6             int cur = left*left + right*right ;
 7             if (cur == c){
 8                 return true ;
 9             }else if (cur < c){
10                 left++ ;
11             }else{
12                 right-- ;
13             }
14         }
15         return false ;
16     }
17 }

 

 
posted @ 2017-11-17 09:54  __Meng  阅读(143)  评论(0编辑  收藏  举报