dec2binary.java 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738
  1. import flanagan.io.KeyboardInput;
  2. import java.math.BigInteger;
  3. import java.lang.Math;
  4. public class dec2binary {
  5. public static void main(String arg[]) {
  6. KeyboardInput kb = new KeyboardInput();
  7. BigInteger decimalNumber = kb.readBigInteger("decimal number =");
  8. int i = 0;
  9. String binary = "";
  10. /* special case when input = 0 */
  11. if (decimalNumber.compareTo(BigInteger.ZERO) == 0) {
  12. System.out.println(0);
  13. System.exit(0);
  14. }
  15. while (true) {
  16. if (decimalNumber.subtract(BigInteger.TWO.pow(i)).compareTo(BigInteger.ZERO) < 0) {
  17. break;
  18. }
  19. i++;
  20. }
  21. for (int j = i - 1; j >= 0; j--) {
  22. if (decimalNumber.subtract(BigInteger.TWO.pow(j)).compareTo(BigInteger.ZERO) < 0) {
  23. binary += "0";
  24. } else {
  25. binary += "1";
  26. decimalNumber = decimalNumber.subtract(BigInteger.TWO.pow(j));
  27. }
  28. }
  29. System.out.println(binary);
  30. System.exit(0);
  31. }
  32. }