首页 > 编程语言 > 详细

[Introduction to programming in Java 笔记] 1.3.7 Converting to binary 十进制到二进制的转换

时间:2016-02-20 00:22:00      阅读:195      评论:0      收藏:0      [点我收藏+]

public class Binary
{
    public static void main(String[] args)
    {   // Print binary representation of N.
        int N = Integer.parseInt(args[0]);
        int v = 1;
        while(v <= N/2)
            v = 2*v;
        // Now v is the largest power of 2 <= N.
        int n = N; // current excess
        while (v > 0)
        { //Cast out the power of 2 in decreasing order.
            if (n < v) { System.out.print(0);    }
            else       { System.out.print(1); n-=v;}
            v = v/2;
        }
        System.out.println();
    }
}

打印10进制数字(decimal number)的二进制表示。将数字拆成2的幂次的和的形式。例如 19 = 16 + 2 + 1. 所以 19 的二进制表示为 10011. 

 

  

[Introduction to programming in Java 笔记] 1.3.7 Converting to binary 十进制到二进制的转换

原文:http://www.cnblogs.com/learning-c/p/5202266.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!