(Easy) Sum of Square Numbers - LeetCode

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;
        
    }
}

 

posted @ 2019-08-29 14:08  CodingYM  阅读(101)  评论(0编辑  收藏  举报