浏览代码

convert binary / decimal programs to BigInteger

Noah Vogt 3 年之前
父节点
当前提交
7d87e0fb02
共有 2 个文件被更改,包括 17 次插入10 次删除
  1. 4 4
      inputOutputFlanagan/binary2dec.java
  2. 13 6
      inputOutputFlanagan/dec2binary.java

+ 4 - 4
inputOutputFlanagan/binary2dec.java

@@ -8,12 +8,12 @@ public class binary2dec{
         KeyboardInput kb = new KeyboardInput();
         String binaryNumber = kb.readLine("binary number =");
 
-        int currentNumber, sum = 0;
+        BigInteger currentNumber, sum = BigInteger.ZERO;
 
         for (int i = 0; i < binaryNumber.length(); i++) {
-            currentNumber = Integer.parseInt(binaryNumber.substring(i,i + 1));
-            if (currentNumber == 1) {
-                sum += Math.pow(2, binaryNumber.length() - i - 1);
+            currentNumber = BigInteger.valueOf(Integer.parseInt(binaryNumber.substring(i,i + 1)));
+            if (currentNumber.compareTo(BigInteger.ONE) == 0) {
+                sum = sum.add(BigInteger.TWO.pow(binaryNumber.length() - i - 1));
             }
         }
 

+ 13 - 6
inputOutputFlanagan/dec2binary.java

@@ -5,27 +5,34 @@ import java.lang.Math;
 public class dec2binary {
     public static void main(String arg[]) {
         KeyboardInput kb = new KeyboardInput();
-        int decimalNumber = kb.readInt("decimal number =");
+        BigInteger decimalNumber = kb.readBigInteger("decimal number =");
 
-        int currentNumber, sum = 0, cur = 0, i = 0;
+        int i = 0;
+        String binary = "";
+
+        /* special case when input = 0 */
+        if (decimalNumber.compareTo(BigInteger.ZERO) == 0) {
+            System.out.println(0);
+            System.exit(0);
+        }
 
         while (true) {
-            if (decimalNumber - Math.pow(2,i) < 0) {
+            if (decimalNumber.subtract(BigInteger.TWO.pow(i)).compareTo(BigInteger.ZERO) < 0) {
                 break;
             }
             i++;
         }
 
-        String binary = "";
         for (int j = i - 1; j >= 0; j--) {
-            if (decimalNumber - Math.pow(2,j) < 0) {
+            if (decimalNumber.subtract(BigInteger.TWO.pow(j)).compareTo(BigInteger.ZERO) < 0) {
                 binary += "0";
             } else {
                 binary += "1";
-                decimalNumber -= Math.pow(2,j);
+                decimalNumber = decimalNumber.subtract(BigInteger.TWO.pow(j));
             }
         }
         
         System.out.println(binary);
+        System.exit(0);
     }
 }