The Artima Developer Community
Sponsored Link

Legacy Java Answers Forum
October 2001

Advertisement

Advertisement

This page contains an archived post to the Java Answers Forum made prior to February 25, 2002. If you wish to participate in discussions, please visit the new Artima Forums.

Message:

Try this code

Posted by Jinaraj on October 29, 2001 at 6:32 AM

> if someone could help with the following it would be greatly appreaciated, problem:
> Write program that allows the user to input a non-negative decimal integer and then displays that value in binary. For example if the user inputs ``13'' the program should output ``1101''.

> Hint: The program should use this strategy:

> Divide the decimal number by 2, keeping the quotient and the remainder (which will be either 0 or 1).
> Prepend the remainder to a string
> Keep dividing and prepending the remainder to the string until the quotient is zero.
> thanks

Try this code
import java.util.*;

class x {

static void main(String ss[]) throws Exception {

int ip = Integer.parseInt(ss[0]);
ArrayList list = new ArrayList();

for (int i=0;;i++) {
int val = ip/2;
int r = ip-(val*2);
list.add(String.valueOf(r));

if (val == 0 || val ==1)
{
list.add(String.valueOf(val));
break;
}
ip = val;
}

StringBuffer buffer = new StringBuffer();

for(int i = list.size()-1; i > -1;i--)
{
buffer.append(list.get(i).toString());
}

System.out.println(buffer.toString());
}
}





Replies:

Sponsored Links



Google
  Web Artima.com   
Copyright © 1996-2009 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use - Advertise with Us