Easy to understand Java solution, without any bit manipulations


  • 1
    public int findComplement(int num) {
            StringBuilder sb = new StringBuilder();
            while (num != 0) {
                sb.append(num % 2 == 0 ? "1" : "0");
                num /= 2;
            }
            return Integer.parseInt(sb.reverse().toStirng(), 2);
        }
    

Log in to reply
 

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