633. Sum of Square Numbers

Posted __Meng

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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 }

 

 

以上是关于633. Sum of Square Numbers的主要内容,如果未能解决你的问题,请参考以下文章

633. Sum of Square Numbers

633. Sum of Square Numbers

[leetcode-633-Sum of Square Numbers]

LeetCode 633. Sum of Square Numbers

[leetcode]633. Sum of Square Numbers

LeetCode Sum of Square Numbers