简体   繁体   English

逐行打印数字位数的递归方法

[英]Recursive method that prints the digits of the number line by line

I'm supposed to use a recursive method to print out the digits of a number vertically. 我应该使用递归方法垂直打印出数字。

For example, if I were to key in 13749, the output would be: 例如,如果我键入13749,输出将是:

1
3
7
4
9

How should I approach this question?? 我应该如何处理这个问题? It also states that I should use the if/else method to check for the base case.. I just started learning java and I'm not really good at it :( 它还指出,我应该使用if / else方法检查基本情况。.我刚刚开始学习Java,但我并不是很擅长:(

import java.util.Scanner;

public class test2 {
  public static void main (String [] args){
    Scanner sc = new Scanner(System.in);
    System.out.print("Enter a positive integer: ");
    int n = sc.nextInt();
    System.out.println();
    System.out.println(numbers(n));  

  } 

public static int numbers(int n){
  int sum;
  if (n == 0) {
    sum = 1;
    } else {

     System.out.println(n%10);
     sum = numbers(n / 10) + (n % 10);


    }
  return sum;
  }      
}

I was asked this question today in an interview! 今天在一次采访中有人问我这个问题!

 public class Sandbox {
   static void prints(int d) {
        int rem = d % 10;
        if (d == 0) {
            return;
        } else {
            prints(d / 10);
        }
        System.out.println(rem);
    }

    public static void main(String[] args) {
        prints(13749);
    }
}

Output: 输出:

1
3
7
4
9

You asked how to approach this, so I'll give you a tip: it would be a lot easier to build up the stack and then start printing output. 您问了如何解决这个问题,所以我给您一个提示:建立堆栈然后开始打印输出会容易得多。 It also doesn't involve manipulating strings, which is a big plus in my book. 它还不涉及操纵字符串,这在我的书中是一个很大的优点。 The order of operations would be: 操作顺序为:

  1. Check for base case and return if it is 检查基本情况并返回是否为
  2. Recursive call 递归调用
  3. Print 打印

This way when you get to the base case, you'll start printing from the tail to the head of the calls: 这样,当您到达基本情况时,将开始从调用的尾部到头部打印:

recursive call 1
    recursive call 2
        recursive call 3
            .... reached base case
        print 3
    print 2
print 1

This way you can simply print number % 10 and make the recursive call with number / 10, the base case would be when number is 0. 这样,您可以简单地打印数字%10并使用数字/ 10进行递归调用,基本情况是数字为0时。

class PrintDigits {

   public static void main(String[] args) {
     String originalNumber, reverse = "";

     // Creating an Scanner object
     Scanner in = new Scanner(System.in);

     System.out.println("Enter a number:");
     // Reading an input 
     originalNumber = in.nextLine();

     // Calculating a length
     int length = originalNumber.length();

     // Reverse a given number
     for ( int i = length - 1 ; i >= 0 ; i-- )
        reverse = reverse + originalNumber.charAt(i);
     //System.out.println("Reverse number: "+reverse);
     digits(Integer.parseInt(reverse));
   }

   /* digits of num */
   public static void digits(int number) {
       if (number == 0)
          System.out.println("");
       else {
          int mode=10;
          System.out.println(+number%mode);
          digits(number/mode);
       }
   }
}

Here is my code in C++ 这是我的C ++代码

Just modify it for Java. 只需针对Java对其进行修改。 You need to show the number after you call the function that way you show the last one first... as per the answer from s.ts 按照s.ts的答案,您需要在调用函数后显示数字,这样才能显示最后一个数字。

void recursive(int n) {
    if (n < 10)
        cout << n << endl;
    else
    {
        recursive(n / 10);
        cout << n % 10 << endl;
    }
}
If number consists of more than one digit print ( n / 10 )

print ( n % 10 )

If you want them printed in the other order 如果要按其他顺序打印

print ( n % 10 )

If number consists of more than one digit print ( n / 10 )

try this 尝试这个

public class Digits {

    public static void main(String[] args) {
        printDigits(13749);
    }

    private static void printDigits(Integer number) {
        int[] m = new int[number.toString().toCharArray().length];

        digits(number, 0, m, 0);

        for (int i= m.length - 1; i>=0; i--) {
            System.out.println(m[i]);
        }
    }

    public static int digits(int number, int reversenumber, int[] m, int i) {

        if (number <= 0) {
            return reversenumber;
        }

        m[i] = (number % 10);
        reversenumber = reversenumber * 10 + (number % 10);
        return digits(number/10, reversenumber, m, ++i);
    }

}

Python example Python示例

def printNoVertically(number):
    if number <  9:
      print(number)
      return
    else:
        printNoVertically(number/10)
        print(number % 10)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM