Merge pull request #793 from obelisk0114/patch

Fix binary to octal conversion
This commit is contained in:
Yang Libin 2019-07-16 09:14:34 +08:00 committed by GitHub
commit efefefddb1
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -16,6 +16,7 @@ public class BinaryToOctal {
*/ */
public static void main(String args[]) { public static void main(String args[]) {
Scanner sc = new Scanner(System.in); Scanner sc = new Scanner(System.in);
System.out.println("Input the binary number: ");
int b = sc.nextInt(); int b = sc.nextInt();
System.out.println("Octal equivalent: " + convertBinaryToOctal(b)); System.out.println("Octal equivalent: " + convertBinaryToOctal(b));
sc.close(); sc.close();
@ -26,18 +27,24 @@ public class BinaryToOctal {
* This method converts a binary number to * This method converts a binary number to
* an octal number. * an octal number.
* *
* @param b The binary number * @param binary The binary number
* @return The octal number * @return The octal number
*/ */
public static int convertBinaryToOctal(int b) { public static String convertBinaryToOctal(int binary) {
int o = 0, r = 0, j = 1; String octal = "";
while (b != 0) { int currBit = 0, j = 1;
r = b % 10; while (binary != 0) {
o = o + r * j; int code3 = 0;
j = j * 2; for (int i = 0; i < 3; i++) {
b = b / 10; currBit = binary % 10;
binary = binary / 10;
code3 += currBit * j;
j *= 2;
} }
return o; octal = code3 + octal;
j = 1;
}
return octal;
} }
} }