Last updated on October 5th, 2024 at 04:20 pm
Here, We see Sum of Square Numbers LeetCode Solution. This Leetcode problem is done in many programming languages like C++, Java, JavaScript, Python, etc. with different approaches.
List of all LeetCode Solution
Topics
Recursion, Tree
Companies
Level of Question
Medium
Sum of Square Numbers LeetCode Solution
Table of Contents
Problem Statement
Given a non-negative integer c, decide whether there are two integers a and b such that a2 + b2 = c.
Example 1:
Input: c = 5
Output: true
Explanation: 1 * 1 + 2 * 2 = 5
Example 2:
Input: c = 3
Output: false
1. Sum of Square Numbers Leetcode Solution C++
class Solution { public: bool judgeSquareSum(int c) { if(c==1 || c==0)return true; for(long int i=0;i*i<=c;i++){ long int x=i*i; if (isPerfectSquare(c-x)) return true; } return false; } bool isPerfectSquare( long int n) { if(n==1 || n==0)return true; long int s=0,e=n; while(s<=e){ long int m=s+(e-s)/2; if(m*m==n)return true; else if(m*m<n) s=m+1; else e=m-1; } return false; } };
2. Sum of Square Numbers Leetcode Solution Java
class Solution { public boolean judgeSquareSum(int c) { long s = 0; long e = (long)Math.sqrt(c); while(s<=e){ long mid = s*s + e*e; if(mid==(long)c){ return true; }else if(mid>(long)c){ e--; }else{ s++; } } return false; } }
3. Sum of Square Numbers Leetcode Solution JavaScript
var judgeSquareSum = function(c) { var r = Math.floor(Math.sqrt(c)); var l = 0; while(l <= r){ var sum = l**2 + r**2 if( sum === c){ return true }else if(sum < c){ l++ }else{ r-- } } return false };
4. Sum of Square Numbers Leetcode Solution Python
class Solution(object): def judgeSquareSum(self, c): cc = int(c ** 0.5) left = 0 right = cc while left <= right: res = left ** 2 + right ** 2 if res == c: return True elif res < c: left += 1 elif res > c: right -= 1 return False