有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java在我的例子中如何删除前导零?

我做了以下练习:

  1. 制作一个将任何数字转换成二进制数的代码
  2. 把那个二进制数倒过来,在屏幕上显示出来
  3. 计算(并在屏幕上显示)二进制数开头有多少个零
  4. 删除该反向二进制数开头的所有零
  5. 将新的二进制数转换回常规数,并在屏幕上显示该数字

目前我被困在第四步,有人能帮我吗?到目前为止,我有:

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");

  }
}

提前感谢:)

我已经得到了答案,第一个人已经帮了我很多。我还将学习并阅读其他答案。不要觉得有必要发布更多回复(当然,除非你想这么做):)


共 (5) 个答案

  1. # 1 楼答案

    这里讨论的每一点都可以看到一个非常简单的解决方案:

    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);
                  
          
    }
    

    输出

    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
    
  2. # 2 楼答案

    只需在字符串中循环并检查字符串的第一个字符,直到不再得到任何零

    检查这个代码

        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
        }
    }
    
  3. # 3 楼答案

    首先,应该使用Scanner并提示用户输入一个数字。查找零的计数相当于查找第一个1(如果没有1,则查找String的长度)。最后,可以使用^{}将二进制文件String解析回int。比如

    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));
    
  4. # 4 楼答案

    要解决第四步的问题,你需要找出这个数字中需要删除的部分

    • 首先,找到字符串的第一个1,它将是您将保留在缩短字符串中的第一个字符
    • 然后只需要将反转字符串中的字符保留在这个字符中,但是一定要检查是否有1,否则您将处理java。lang.StringIndexOutOfBoundsException,因为indexOf()如果没有匹配,则返回-1:
    
        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;
    
    

    既然这是一个练习,我就到此为止,如果你需要第五部分的帮助,请随意评论

  5. # 5 楼答案

    我会用正则表达式:

    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]*", ""));
        }
    }
    

    输出:

    0010011
    10011