【问题标题】:Printing number using recursion in java without its biggest digit在java中使用递归打印数字而没有最大数字
【发布时间】:2019-04-10 20:51:17
【问题描述】:

使用递归,我需要输入一个数字,控制台将打印这个数字而没有最高位。如果小于 10,则返回 0。

我已经找到了最大的数字,但是我怎样才能删除它并在没有它的情况下打印数字? 这是最大数字的代码:

public static int remLastDigit(int n){

        if(n==0)                              
            return 0;
        return Math.max(n%10, remLastDigit(n/10)); 

    }

如果我输入 12345,我希望输出为 1234。如果我输入 9 或更少,我希望输出为 0。

【问题讨论】:

  • If it's smaller than 10 表示n<10
  • 输入将是一个或多个数字?因为使用递归你可以接受多个输入。
  • 只有一个号码。例如 6342

标签: java recursion


【解决方案1】:

这是我的解决方案:

// call this method
public static int removeLastDigit(int number) {
    return removeLastDigitImpl(number, largestDigit(number));
}

private static int removeLastDigitImpl(int number, int largestDigit) {
    if (number < 10) { // if the number is a single digit, decide what to do with it
        if (number == largestDigit) {
            return 0; // if it is the largest digit, remove it
        } else {
            return number; // if it is not, keep it
        }
    }
    // handle the last digit of the number otherwise
    if (number % 10 == largestDigit) {
        // removing the digit
        return removeLastDigitImpl(number / 10, largestDigit);
    } else {
        // not removing the digit
        return removeLastDigitImpl(number / 10, largestDigit) * 10 + number % 10;
    }
}

// this is the same as your attempt
private static int largestDigit(int n){

    if(n==0)
        return 0;
    return Math.max(n%10, largestDigit(n/10));

}

【讨论】:

    【解决方案2】:

    既然您已经很好地找到了最大数字,那么您可以在没有它的情况下打印该数字。

        public static void main(String[] args) {
            printWithoutDigit(2349345, remLastDigit(2349345));
        }
    
        public static void printWithoutDigit(int number, int maxDigit) {
            Integer.toString(number).chars().filter(digit -> Integer.valueOf(String.valueOf((char)digit))!=maxDigit).forEach(d -> System.out.print((char)d));
        }
    

    【讨论】:

      【解决方案3】:

      您可以将您的数字转换为字符串,或者更准确地说,转换为字符数组。然后,您可以找出该数组中最大数字的位置,将其删除并将您的 char 数组转换回整数。

      大概是这样的:

      int num = 12345; //the number from which you want to remove the biggest digit
      char[] numC = String.valueOf(num).toCharArray();
      int biggestDigit = 0;
      int biggestDigitIndex = 0;
      for (int i = 0; i < numC.length; i++) {
          if (biggestDigit < Character.getNumericValue(numC[i])) {
              biggestDigit = Character.getNumericValue(numC[i]);
              biggestDigitIndex = i;
          }
          //Remove digit at index biggestDigitIndex from numC
          //Convert numC back to int
      }
      

      当然,您必须将其合并到您的递归中,这意味着在将 numC 转换回 int 后返回您得到的数字,然后再次将其输入到您的输入参数中。另外,当然您需要添加一个检查,如果您的号码开头是

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-09-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-01-13
        • 2023-02-18
        • 1970-01-01
        • 2018-02-18
        相关资源
        最近更新 更多