C++ using 1+ 3 + 5 + ... + (2n -1) logic


  • 0
    T
    /*
    1 = 1;
    4 = 1 + 3;
    9 = 1 + 3 + 5;
    ...
    n^2 = 1 + 3 + 5 + ... + (2*n - 1)
    
    so, we need to calculate the number of step which leads n - 1 - 3 - 5 - ... -(2*n -1) = 0
    */
    
    class Solution {
    public:
        int mySqrt(int x) {
            int i = 1;
            int res = 0;
            
            while (x >= 0) {
                x -= i;
                i += 2;
                res++;
            }
            
            return res - 1;
        }
    };
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.