Easy one line with toBinaryString and replace


  • 0
    R

    Easy solution

    public class Solution {
        public int findComplement(int num) {
            return Integer.parseInt(Integer.toBinaryString(num).replace("0","2").replace("1","0").replace("2","1"),2);
        }
    }
    

    Steps:
    1)num = 5
    2)toBinaryString = 101 //convert in binary string
    3)replace("0","2") = 121 //is possible use any letter or number
    4)replace("1","0") = 020
    5)replace("2","1") = 010
    6)parseint("010",2) = 2 //convert to int using base 2


Log in to reply
 

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