java - 递归 - Kata 挑战

标签 java recursion

挑战是删除数字末尾的零。两个数字内的零是可以的。例如:

14000 == 14 //all end zeros removed
10300 == 103 // all end zeros removed

我写这个函数来解决这个问题:

    public class NoBoring {
    public static int noBoringZeros(int n) {
      System.out.println(n); // testing 
      System.out.println(Math.abs(n % 10)); //testing
        if(Math.abs(n % 10) != 0){
          return n;
        }
      return noBoringZeros(n/10);
    }
}

不幸的是,这不适用于负输入。请参阅下面的测试用例的输出:

//LD = last digit of the number
//ZR is the zero removed
        Fixed Tests: noBoringZeros
    1450
    0 //LD
    145 //ZR
    5 //LD
    960000 
    0 //LD
    96000 //ZR
    0 //LD
    9600 //ZR
    0 //LD
    960 //ZR
    0 //LD
    96 //ZR
    6 //LD
    1050
    0 //LD
    105 //ZR
    5 //LD
    -1050
    0 //LD
    -105 //ZR
    5 //LD
    -105 
    5
    0
    0
    0
    0
    0
    0
    0
    0
    0
    0
    0
    0
    0
    0
    0
    0
    0
    0
    0
    0
    0
    0
    0
    0

我不完全明白为什么会失败?我本以为 n % 10 not = 0 的 drop out 语句会导致 n 返回,但对于负数似乎不会这样做?

最佳答案

如果您不熟悉数学函数,您可以使用字符串函数:

     int n = -22400 ; // You want -224           
     String str = String.valueOf(n);

     while(str.endsWith("0")){

            if (str != null && str.length() > 0 && str.charAt(str.length()-1)=='0') {

                 str = str.substring(0, str.length()-1);
            }

        }

     System.out.println(Integer.parseInt(str));

关于java - 递归 - Kata 挑战,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36778317/

相关文章:

c - 如何获取C中子目录的总大小?

计算阶乘的C程序

python - 如何使此方法非递归?

java tensorflow reset_default_graph

java - 是否可以从用户模式 ​​java 应用程序查询特权 Windows 服务?

c - 递归查找数组的最大元素

java - 查询递归中此变量的使用情况

java - 高性能并发 MultiMap Java/Scala

java - 如何更改 war 文件中 index.jsp 的位置

java - 对抓取 HTML 标签正则表达式模式感到困惑