10进制 VS 2进制

10进制 VS 2进制

http://www.nowcoder.com/questionTerminal/fd972d5d5cf04dd4bb4e5f027d4fc11e

  • 利用Java大数即可,详情请看代码
import java.math.BigInteger;
import java.math.BigDecimal;
import java.util.Scanner;
import java.util.Vector;



public class Main {
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Scanner sc = new Scanner(System.in);
        while(sc.hasNextLine()) {
            String n = sc.nextLine();
            BigInteger x = new BigInteger(n);//将读入的字符串赋值为大数
            BigInteger res = BigInteger.ZERO; //结果变量
            int len = x.bitLength(); // 计算二进制表示时总位数
            int cnt = 1;//当前数字是第几位
            //System.out.println(x + " len = " + len);
            while(x.compareTo(BigInteger.ZERO) == 1) {
                BigInteger r = x.mod(BigInteger.valueOf(2));//取低位
                x = x.shiftRight(1);//向右移位
                res = res.add(r.multiply(BigInteger.ONE.shiftLeft(len - cnt)));//结果要加上该位数值乘以该位权重,因为是逆置所以幂次是len-cnt
                cnt++;
            }
            System.out.println(res);
        }
        sc.close();

    }

}

全部评论

相关推荐

迷茫的大四🐶:你这个拿去投央国企吧,投私企包过不了的
点赞 评论 收藏
分享
迷茫的大四🐶:价格这么低都能满了?
点赞 评论 收藏
分享
评论
1
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务