java three solutions


  • 0

    First idea Native solution

    public class Solution {
        public int findComplement(int num) {
            int ret=0;
            int step=0;
            while(num!=0)
            {
              ret|=((num&1)^1)<<step++;
              num=num>>1;
            }
            return ret;
        }
    }
    

    Further

    public class Solution {
        public int findComplement(int num) {
           int mask=0;
           int temp=num;
           while(temp!=0)
           {
            mask=(mask<<1)|1;
            temp>>=1;
           }
           return (-1^num)&mask;
        }
    }
    

    Other people's solution

    public class Solution {
        public int findComplement(int num) {
            return (~num)&((Integer.highestOneBit(num)<<1)-1);
        }
    }
    

Log in to reply
 

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