Skip to content

Commit

Permalink
Sync LeetCode submission - Perfect Squares (cpp)
Browse files Browse the repository at this point in the history
  • Loading branch information
pradeeptosarkar committed Feb 8, 2024
1 parent 3dad691 commit d190e4f
Showing 1 changed file with 22 additions and 71 deletions.
93 changes: 22 additions & 71 deletions LeetCode/problems/perfect_squares/solution.cpp
Original file line number Diff line number Diff line change
@@ -1,76 +1,27 @@
/*class Solution {
public:
int numSquares(int n) {
}
};*/

class Solution {

public:

int numSquares(int n) {

int count=0;

queue<int> q;

q.push(n);

while(!q.empty()) {

int n=q.size();

for(int i=0; i<n; i++) {

int curr=q.front();

q.pop();

long long int a=sqroot(curr);

if(a*a==curr)

return count+1;

for(int j=a; j>0; j--)

q.push(curr-j*j);

int numSquares(int n)
{
int sqrtVal=(int)sqrt(n);

if(sqrtVal*sqrtVal==n)
return 1;

while(n%4==0)
n/=4;

if(n%8==7)
return 4;

for(int i=1;i*i<=n;i++)
{
int a=i*i;
int b=(int)sqrt(n-a);

if(b*b==n-a)
return 2;
}

count++;

}

return count;

}

long long int sqroot(int n) {

int low=0, high=n;

while(low<=high) {

long long int mid=low+(high-low)/2;

if(mid*mid==n)

return mid;

else if(mid*mid>n)

high=mid-1;

else

low=mid+1;


return 3;
}

return high;

}

};

0 comments on commit d190e4f

Please sign in to comment.