繁体   English   中英

递归如何工作以及如何使用递归来操作 integer 位数字?

[英]How does recursion work and how can recursion be used to manipulate integer digits?

我正在努力学习 java,递归我似乎无法理解。 我可以理解递归如何用于添加和执行其他基本数学运算,但递归如何用于反向操作整数和单个 integer 数字。

示例:一个方法采用单个正 integer 参数并显示其基数 5 等价物。 231 返回 1411 但下面的代码返回 1141。我将如何反转整数的顺序?

public void base5(int n){
    int rem=n%5;
    int vis=n/5;
    if(n!=0){
   //   System.out.print(rem/*+"|"*/);
    // 

// rem=(rem+rem)*10;
       //   System.out.print("\n||"+n+"||\n");
System.out.print(rem);
         base5(vis);
          }
    else{
     
      return;
    }
  } 

从右到左获取 integer 的各个数字的算法是众所周知的。 请参阅如何获取 int 数字的单独数字? .

我不会“解释”递归,但我会给你第一个问题的一个可能的解决方案:

一种方法采用单个正数 integer 并以每三位数字插入逗号的方式显示它

import java.util.Scanner;
class Main {

  public static void main( String [] args) {
    Scanner sc = new Scanner(System.in);
    
    System.out.print("Enter your positive integer: ");
    long number = sc.nextLong();    
    String result = addCommas(number);
    System.out.println(result);
  } 

  public static String addCommas(long num) {
    return addCommas(num, 1);
  }
  
  public static String addCommas(long num, int counter) {
    if (num == 0) {
      return ""; // base case ends recursion
    }
    else {
      long digit = num % 10;      
      num = num / 10;
      String comma = (counter%3==0 && num>0) ? "," : "";
      // recursive call below because we call addCommas() again
      return addCommas(num, counter+1) + comma + digit;
    }    
  }
  
}

这是第二个问题的紧凑解决方案:

一种方法采用单个正数 integer 并显示反转其数字的结果

  public static String reverseDigits(long num) {
    if (num == 0) { 
      return "";
    }
    else {
      return String.valueOf(num % 10) + reverseDigits(num / 10);
    }
  }

暂无
暂无

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

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