By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
455,806 Members | 1,380 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 455,806 IT Pros & Developers. It's quick & easy.

How to Print Binary of a Decimal Number

P: 6
Any one Write this Program in a Better Way ..

Expand|Select|Wrap|Line Numbers
  1. /*******
  2. *@Author Lokanath Behera
  3. *@Mob-[removed]
  4. *@Email-[removed]@gmail.com
  5. *****/
  6.  
  7. class Binary{
  8.     public static void main(String[] args){
  9.         int no=19999;
  10.         int i=0;
  11.         int size=no/2;
  12.         int a[]=new int[++size];
  13.         while(no>0){
  14.  
  15.         if(no%2==0){
  16.             a[i++]=0;
  17.         }
  18.         else{
  19.             a[i++]=1;
  20.  
  21.         }
  22.         no /=2;
  23.         }
  24.  
  25.         for(int j=i-1;j>=0;j--){
  26.  
  27.             System.out.print(a[j]);
  28.  
  29.         }
  30.     }
  31. }
  32.  
May 5 '13 #1
Share this Question
Share on Google+
3 Replies


Nepomuk
Expert 2.5K+
P: 3,112
Define better. For example, an elegant way would be to do it recursively.
Even keeping with the loop approach, the length of the array can be calculated more accurately with
Expand|Select|Wrap|Line Numbers
  1. // The length will be the logarithm of no to base 2, plus 1
  2. int size = Math.log(no) / Math.log(2) + 1;
There are also ways to calculate logarithms to the base 2 more efficiently, so you could use those if efficiency is relevant.
Does that cover it or is there a specific way in which you want it improved?
May 6 '13 #2

100+
P: 158
Hey lokanath60, there is no need of if-else statement inside the while loop.
May 6 '13 #3

Nepomuk
Expert 2.5K+
P: 3,112
Good point, you could just use
Expand|Select|Wrap|Line Numbers
  1. while(no > 0){
  2.   a[i++] = no % 2;
  3.   no /=2;
  4. }
May 6 '13 #4

Post your reply

Sign in to post your reply or Sign up for a free account.