码迷,mamicode.com
首页 > 其他好文 > 详细

633. Sum of Square Numbers

时间:2017-11-17 10:51:49      阅读:120      评论:0      收藏:0      [点我收藏+]

标签:xpl   nat   math   integer   pre   res   code   output   amp   

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

标签:xpl   nat   math   integer   pre   res   code   output   amp   

原文地址:http://www.cnblogs.com/mengchunchen/p/7850131.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!