Skip to content

Commit efefefd

Browse files
authored
Merge pull request TheAlgorithms#793 from obelisk0114/patch
Fix binary to octal conversion
2 parents acb40ef + 48537fc commit efefefd

File tree

1 file changed

+16
-9
lines changed

1 file changed

+16
-9
lines changed

Conversions/BinaryToOctal.java

Lines changed: 16 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@ public class BinaryToOctal {
1616
*/
1717
public static void main(String args[]) {
1818
Scanner sc = new Scanner(System.in);
19+
System.out.println("Input the binary number: ");
1920
int b = sc.nextInt();
2021
System.out.println("Octal equivalent: " + convertBinaryToOctal(b));
2122
sc.close();
@@ -26,18 +27,24 @@ public static void main(String args[]) {
2627
* This method converts a binary number to
2728
* an octal number.
2829
*
29-
* @param b The binary number
30+
* @param binary The binary number
3031
* @return The octal number
3132
*/
32-
public static int convertBinaryToOctal(int b) {
33-
int o = 0, r = 0, j = 1;
34-
while (b != 0) {
35-
r = b % 10;
36-
o = o + r * j;
37-
j = j * 2;
38-
b = b / 10;
33+
public static String convertBinaryToOctal(int binary) {
34+
String octal = "";
35+
int currBit = 0, j = 1;
36+
while (binary != 0) {
37+
int code3 = 0;
38+
for (int i = 0; i < 3; i++) {
39+
currBit = binary % 10;
40+
binary = binary / 10;
41+
code3 += currBit * j;
42+
j *= 2;
43+
}
44+
octal = code3 + octal;
45+
j = 1;
3946
}
40-
return o;
47+
return octal;
4148
}
4249

4350
}

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy