首页 > 其他 > 详细

(Easy) Sum of Square Numbers - LeetCode

时间:2019-08-29 14:20:48      阅读:63      评论:0      收藏:0      [点我收藏+]

Description:

 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

 

Accepted
49,426
Submissions
151,388

Solution:

class Solution {
    public boolean judgeSquareSum(int c) {
        
        for(int i = 0; i<= (int)Math.sqrt(c);i++)
            for(int j = 0; (int)j<=Math.sqrt(c); j++){
                
                if(i*i+j*j ==c){
                 System.out.println("i= "+i+" j = "+j);
                    return true;
                }
            }
        
        return false;
        
    }
}

 

1. Naive Brutal search,

Will work for large proportion of the test cases, but would have overflow or Time Limit Exception 

技术分享图片

 

Accepted Solution:

class Solution {
    public boolean judgeSquareSum(int c) {
      int begin = 0; 
      int end = (int) Math.sqrt(c);
        
        while (begin<=end){
        
            int tmp = begin*begin + end * end; 
           
            if(tmp< c){
                begin++;            
            }
            else if(tmp >c){
                end--;
            }
            
            else{
                return true;
            }
              
        }
        
        return false;
        
    }
}

 

(Easy) Sum of Square Numbers - LeetCode

原文:https://www.cnblogs.com/codingyangmao/p/11429387.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!