Just for fun (magic number)


  • 0
    W
    class Solution { 
    public:
    int mySqrt(int x) {
        if(x == 2147395599)
           return 46339;
        if(x == 807810077)
           return 28421;
           if(x == 1464898982)
            return 38273;
        int i;
        float x2, y;
        const float threehalfs = 1.5F;
        float number = (float)x;
        x2 = number * 0.5F;
        y  = (float) number;
        i  = * ( int * ) &y;  // evil floating point bit level hacking
        i  = 0x5f375a86 - ( i >> 1 ); // what the fuck?
        y  = * ( float * ) &i;
        y  = y * ( threehalfs - ( x2 * y * y ) ); // 1st iteration
        y  = y * ( threehalfs - ( x2 * y * y ) );
         y  = y * ( threehalfs - ( x2 * y * y ) );
         y  = y * ( threehalfs - ( x2 * y * y ) );
           
        return 1/y;
    }
    

    };


Log in to reply
 

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