首页 文章

递归方法,返回给定整数的位数

提问于
浏览
0

需要编写一个返回整数的位数的方法 .

起初我使用迭代方法完成它并且一切工作都很好,但是,当我想使用递归编辑代码时我总是卡在第一次计数并且无法弄清楚原因 . 任何帮助深表感谢..

public static int numberLength(int n) {
    if (n < 0) {
      n *= (-1);
    } else if (n == 0) {
      return 1;
    }

    int digits = 0;
    if (n > 0) {
      digits += 1;
      numberLength(n / 10);
    }
    return digits;

3 回答

  • 2

    在递归方法中,您需要根据减小输入值的大小返回一些值,并将其与当前计数结合起来,例如:

    public static int numberLength(int n){ 
       if(n < 10){ 
         return 1; 
       } 
    
       return 1 + (numberLength(n/10)); //This line combines the result
    }
    
  • 0

    问题是你要丢弃 numberLength(n / 10); 的结果

    你可能打算输入:

    int digits = 0;
    if (n > 0) {
      return 1 + numberLength(n / 10);
    }
    return digits;
    
  • 0

    可能的解决方案可能如下所示:

    public static int numberLength(int n){
    
        if(n < 0){
            return numberLength(-n);
        }
    
        else if(n == 0){
            return 0;
        }
        else{
            return 1 + numberLength(n/10);
        }
    }
    
    public static void main(String[] args){
        System.out.println(numberLength(-152555)); //returns 6
    }
    

相关问题