码迷,mamicode.com
首页 > 其他好文 > 详细

1012.十进制整数的补码

时间:2019-07-08 13:48:30      阅读:70      评论:0      收藏:0      [点我收藏+]

标签:十进制   基本   com   scan   src   image   har   port   进制   

技术图片
自己的方法不适用性太差了 因为要另外处理0;
所以不建议采用

import java.util.Scanner;
class Solution {
      public int bitwiseComplement(int N) {
            String str = "";
            int sum = 0 ;
            if(N == 0) {
                return 1;
            }
            while( N >0 ) {
                if(N % 2 == 0) {
                    str = 1 + str;
                }
                else {
                    str = 0 + str ;
                }
                N /= 2;
            }
            for(int i = 0 ; i <str.length(); i++) {
                if(str.charAt(i) == '1') 
                    sum = (sum)*2 +1;
                else
                    sum = (sum)*2 +0;
            }
            return sum;
        }
}

其他版本 emmmm 也是要另外处理 0 和 1 不过他方法确实挺好的 采用了位运算 get~~~~

class Solution {
    public int bitwiseComplement(int N) {
        int i, M=N;
        for (i=1 ; i<=N ; i<<=1){
            M = M^i;
        }
        return N==0 ? 1 : M ;
    }
}

第二种位运算 很ok 基本都是这种思路

public int bitwiseComplement(int N) {
        if (N == 0) return 1;
        int ones = 0, tmp = N;
        while (tmp != 0) {
            tmp = tmp >> 1;
            ones = ones << 1;
            ++ones;
        }
        return N ^ ones;
    }

1012.十进制整数的补码

标签:十进制   基本   com   scan   src   image   har   port   进制   

原文地址:https://www.cnblogs.com/cznczai/p/11150420.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!