美文网首页
Number Completement

Number Completement

作者: yfmei | 来源:发表于2017-04-01 15:32 被阅读0次
    /**
     * kaggle 476
     * Input: 5
     * Output: 2
     * Explanation: 
     *      The binary representation of 5 is 101 (no leading zero bits), 
     *      and its complement is 010. 
     *      So you need to output 2.
     * @author yfmei
     *
     */
    
    public class NumberCompletement {        
            public static void main(String[] args) {
            char[] chr = Binary.toBin(2);
            char[] afterChr = new char[chr.length] ;
            int i = 0;
            for(char c : chr){
                c = (char) ('0' == c ?'1':'0'); 
                afterChr[i] = c;
                i++;
            }
            int n = Binary.toInt(afterChr);
            System.out.println(n);
        }
    
            /**
         * 二进制转换成十进制的方法是
         * 1、从最低位(右边)开始计算 : 位上的值 * 2^(位数-1)
         * @param binaryStr
         * @return
         */
        public static int toInt(char[] binChr) {
            int sum = 0;
            for(int i = binChr.length-1,j = 1;i>=0;i--,j++){
                int num = Integer.parseInt(""+binChr[i]);
                sum += num*Math.pow(2,j-1);
            }
            return sum;
        }
        
        /**
         * 十进制转换成二进制
         * @param x
         * @return
         */
        public static char[] toBin(int x) {
            String xStr = "" ;
            while(x > 0){
                xStr = ((x %2 == 0?"0":"1")+xStr);
                x = x / 2;
            }   
            return xStr.toCharArray();
        }
    }
    

    相关文章

      网友评论

          本文标题:Number Completement

          本文链接:https://www.haomeiwen.com/subject/enviottx.html