简体   繁体   中英

Methods - Convert Integer to Binary

Prompt: I need to create code using 2 methods to convert an Integer to binary. This is on zybooks and it has run successfully but it is saying some some of the output is wrong. My code:

public static String intToReverseBinary(int integerValue) { 
  String reverseBinary = ""; 
  int x = integerValue; 
  while (x != 0) { 
     int remainder = x % 2;  
     x = x /2; 
     reverseBinary = reverseBinary + Integer.toString(remainder); 
  } 
  return stringReverse(reverseBinary);
}

public static String stringReverse(String inputString) { 
  String reversed = ""; 
  for (int i = inputString.length() - 1; i >= 0; i--) { 
     reversed = reversed + inputString.charAt(i); 
  } 
  return reversed; 
}


public static void main(String[] args) {
  Scanner scnr = new Scanner(System.in); 
  int userInput = scnr.nextInt(); 
  System.out.println(intToReverseBinary(userInput)); 
}

It says: Convert 19 to binary using intToReverseBinary() and stringReverse() Your output intToReverseBinary(19) incorrectly returned 10011. But isn't that correct?

import java.util.Scanner; 

public class LabProgram {
   
   /* Define your methods here */ 
   public static String intToReverseBinary(int integerValue){
      String reverseBinary="";
      while (integerValue>0){
         int remainder = integerValue % 2;  
         integerValue = integerValue /2; 
         reverseBinary = reverseBinary + Integer.toString(remainder);
         
      }
      return reverseBinary;
   }
   public static String stringReverse(String inputString){
      String reversed = ""; 
      for (int i = inputString.length() - 1; i >= 0; i--) { 
      reversed = reversed + inputString.charAt(i); 
   } 
      return reversed; 
   }
   
   public static void main(String[] args) {
      
         Scanner s= new Scanner(System.in);
         int userint;
         userint=s.nextInt();
         System.out.println(stringReverse((intToReverseBinary(userint))));
         
         
         
   }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM