Different solutions | C++


  • 0
    Z
    • solution1: deal with every digit
    • solution2: $2^k$ xor num [6ms]
            signed int a[32], ns = 0, n = num >> 1;
            a[0] = 0; a[1] = 1; a[2] = 3; a[3] = 7;
            a[4] = 15; a[5] = 31; a[6] = 63; a[7] = 127;
            a[8] = 255; a[9] = 511; a[10] = 1023; a[11] = 2047;
            a[12] = 4095; a[13] = 8191; a[14] = 16383; a[15] = 32767;
            a[16] = 65535; a[17] = 131071; a[18] = 262143; a[19] = 524287;
            a[20] = 1048575; a[21] = 2097151; a[22] = 4194303; a[23] = 8388607;
            a[24] = 16777215; a[25] = 33554431; a[26] = 67108863; a[27] = 134217727;
            a[28] = 268435455; a[29] = 536870911; a[30] = 1073741823; a[31] = 2147483647;
    
            while (n>0){
                ns = ns + 1;
                n = n >> 1;
            }
            return num^a[ns+1];
    
    • solution3: similar ideal with clever implementation
            //Attention: unsigned
            unsigned mask = ~0;
            while (num & mask) // true == 1 == mask/2>num
                mask <<= 1;
            return ~mask & ~num; //3ms
            //return ~mask ^ num; //3ms, I prefer this one, combining solution2&3
    

Log in to reply
 

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