File tree Expand file tree Collapse file tree 1 file changed +16
-9
lines changed Expand file tree Collapse file tree 1 file changed +16
-9
lines changed Original file line number Diff line number Diff 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}
    
 
   
 
     
   
   
          
     
  
    
     
 
    
      
     
 
     
    You can’t perform that action at this time.
  
 
    
  
     
    
      
        
     
 
       
      
     
   
 
    
    
  
 
  
 
     
    
0 commit comments