您的位置:首页 > 其它

633. Sum of Square Numbers

2017-11-17 09:54 323 查看

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 }

 

 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: