Home > Mobile >  How to remove the leading zeros in my case?
How to remove the leading zeros in my case?

Time:10-04

I got the following exercise:

  1. Make a code that converts any number into a binary number
  2. Reverse that binary number and show it on screen
  3. Count (and show on screen) how many zeros there are at the beginning of the binary number
  4. Remove all the zeros at the beginning of that reversed binary number.
  5. Convert the new binary number back to a regular number and show that number on screen.

Currently I am stuck at step 4, can somebody please help me? Thus far I have this:

import java.util.*;


class Main {
  public static void main(String[] args) {

  int woord = 100;

    
  String bin = Integer.toBinaryString(woord);
  String test = new StringBuilder(bin).reverse().toString();

  System.out.println(test);

  String[] parsed = test.split("1");
  System.out.println(parsed.length > 0 ? parsed[0].length() : "0");

  }
}

Thanks in advance :)

I have got the answer, the first person already helped me a ton. I will be learning from and reading the other answers as well. Don't feel the need to post more replies (unless you want to ofcourse) :)

CodePudding user response:

First, you should use a Scanner and prompt the user to enter a number. Finding the count of zeros is equivalent to finding the first 1 (or the length of the String if there isn't a 1). Finally, you can use Integer.parseInt(String, int) to parse a binary String back to an int. Like,

Scanner scan = new Scanner(System.in);
System.out.print("Enter a number: ");
System.out.flush();
int val = scan.nextInt();
String bin = Integer.toBinaryString(val);
String rev = new StringBuilder(bin).reverse().toString();
System.out.println(rev);
int count = rev.indexOf('1');
if (count < 0) {
    count = rev.length();
}
System.out.println(count);
System.out.println(Integer.parseInt(rev.substring(count), 2));

CodePudding user response:

To solve the fourth step you need to figure out what is the portion of this number that you need to remove.

  • First, find the first 1 of your String, it will be the first character that you will keep in your shortened String.
  • Then need to only keep the characters of your reversed String from this character but be sure to check if there is a 1 otherwise you will deal with an java.lang.StringIndexOutOfBoundsException since indexOf() returns -1 if no match has been made:

    int firstOne = test.indexOf('1');
    
    String shortened;

    if(firstOne >=0) //indexOf method returns -1 if no match has been found
       shortened = test.substring(firstOne);
    else 
       shortened = test;

Since it is an exercise you got i will stop here, feel free to comment if you need help for part 5.

CodePudding user response:

I would just use regex:

class Main {
    public static void main(String[] args) {

        int woord = 100;


        String bin = Integer.toBinaryString(woord);
        String test = new StringBuilder(bin).reverse().toString();

        System.out.println(test);
        System.out.println(test.replaceAll("^[0]*", ""));
    }
}

Output:

0010011
10011

CodePudding user response:

Every point is covered here see a very simple solution:

public static void main(String[] args) {

    Scanner scan = new Scanner(System.in);
    System.out.print("Enter a number: ");
    int inputDecimalNumber = scan.nextInt();

    System.out.println("Input number in decimal: " inputDecimalNumber);
    
     //1.  Make a code that converts any number into a binary number        
     String inputBinary = Integer.toBinaryString(inputDecimalNumber);
     System.out.println("Input number in binary : " inputBinary);
     
     //2. Reverse that binary number and show it on screen
      String reverseBinary = new StringBuilder(inputBinary).reverse().toString();
      System.out.println("Reverse binary number: " reverseBinary);

     //3. Count (and show on screen) how many zeros there are at the beginning of the binary number
      int leadingZeros = reverseBinary.indexOf("1") > 0 ? reverseBinary.indexOf("1") : 0;
      System.out.println("Leading zeroes count in reverse binary : " leadingZeros);

     //4. Remove all the zeros at the beginning of that reversed binary number.
      String reverseBinaryAfterRemovingLeadingZeros = reverseBinary.substring(reverseBinary.indexOf("1"));
      System.out.println("Reverse binary after removing leading zeroes : "  reverseBinaryAfterRemovingLeadingZeros);
      
     //5. Convert the new binary number back to a regular number and show that number on screen.
      int decimalValue=Integer.parseInt(reverseBinaryAfterRemovingLeadingZeros,2);
      System.out.println("Reverse binary into decimal number : " decimalValue);
              
      
}

OUTPUT

Enter a number: 38
Input number in decimal: 38
Input number in binary : 100110
Reverse binary number: 011001
Leading zeroes count in reverse binary : 1
Reverse binary after removing leading zeroes : 11001
Reverse binary into decimal number : 25

CodePudding user response:

Just loop through the string and check the first character of the string until you don't get any zeros anymore,

check this code

    public static void main(String[] args) {
    int woord = 100;

    // step 1
    String bin = Integer.toBinaryString(woord);
    // step 2
    String test = new StringBuilder(bin).reverse().toString();
    System.out.println(test);
    // step 3

    String[] parsed = test.split("1");
    System.out.println(parsed.length > 0 ? parsed[0].length() : "0");

    // step 4

    for (int i = 0; i < test.length(); i  ) {
        char c = test.charAt(i);
        if (c == '0') {
            test = test.replaceFirst("0", "");
            System.out.println(test);
        }
        //Process char
    }
}
  •  Tags:  
  • java
  • Related