Advertisement
nikunjsoni

279-2

Jun 8th, 2021 (edited)
81
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.58 KB | None | 0 0
  1. class Solution {
  2. public:
  3.     bool check(int n){
  4.         int sq = sqrt(n);
  5.         return (sq*sq) == n;
  6.     }
  7.    
  8.     int numSquares(int n) {
  9.         // If perfect square, return 1.
  10.         if(check(n))
  11.             return 1;
  12.        
  13.         // If n = 4^k(8m+7), return 4.
  14.         while(n%4 == 0)
  15.             n /= 4;
  16.         if(n%8==7)
  17.             return 4;
  18.        
  19.         // If n is sum of 2 square, return 2.
  20.         for(int i=1;i*i<=n;i++)
  21.             if(check(n-(i*i)))
  22.                 return 2;
  23.        
  24.         // Else return 3.
  25.         return 3;
  26.     }
  27. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement