gpt4 book ai didi

java - Java中如何使用递归求数字之和?

转载 作者:行者123 更新时间:2023-12-01 16:24:06 24 4
gpt4 key购买 nike

我需要创建一个程序来计算正整数的数字之和。用户应输入一个正整数,程序应显示其数字之和。程序的输出应该是:

Please input a positive integer number N: 2563

Sum of all digits of the number 2563 is: 16

到目前为止,我已经正确地完成了此操作,但是我不确定如何使用递归重新创建该程序。任何帮助将不胜感激。

这是迄今为止我的代码:

import java.util.Scanner;

public class SumOfDigits {

public static void main(String[] args) {

int N = 0;
int x = 0;
int sum = 0;

Scanner keyboard = new Scanner(System.in);

System.out.println("******");
System.out.println();
System.out.print("Please enter a positive integer number N: ");

N = keyboard.nextInt();

int M = N;

while(N > 0) {

x = N % 10;

sum = sum + x;

N = N / 10;
}


System.out.println();
System.out.println("Sum of all digits of the number " + M + " is: " + sum);
System.out.println();
keyboard.close();
}


}

最佳答案

要使用递归解决问题,您必须将问题分解为一个较小的问题(或几个较小的问题),并使用较小问题的解来找到原始问题的解。

在数字和的情况下,有几种方法可以解决这个问题。

最简单的可能是删除最后一位数字,解决较小数字的问题,并将最后一位数字添加到较小数字的数字和中。

在伪代码中(我将实际的编码留给您),它看起来像这样:

sumOfDigits (x)
if (x < 10)
return x
last = x % 10 // extract the last digit
return last + sumOfDigits (x/10) // recursively find the sum of digits of the first n-1
// digits and add the last digit

关于java - Java中如何使用递归求数字之和?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62189700/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com