Easy-to-understand solution without fancy ideas


  • 0
    G
    public class Solution {
        public static int findComplement(int num) {
            
            int n = 0;
            StringBuilder sb = new StringBuilder();
            StringBuilder revsb = new StringBuilder();
            
            while (num > 0) {
                sb.append(num % 2);
                num = num / 2;
            }
            
            String s = sb.reverse().toString();
            
            for (int i=0; i<s.length(); i++) {
                if (s.charAt(i)=='0') revsb.append('1');
                if (s.charAt(i)=='1') revsb.append('0');
            }
            
            String rev = revsb.toString();
            
            for (int j=0; j<rev.length(); j++) {
                n += Character.getNumericValue(rev.charAt(j)) * Math.pow(2,rev.length()-j-1);
            }
            return n;
        }
    } 
    

Log in to reply
 

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