-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Sync LeetCode submission - Perfect Squares (cpp)
- Loading branch information
1 parent
3dad691
commit d190e4f
Showing
1 changed file
with
22 additions
and
71 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | ||
|
||
} | ||
|
||
}; |