Java递归实现整数各位求和

Java小练习:递归实现整数各位求和

入门练习题

  • 课后习题遇到了求0-1000以内整数各位之和的问题,先是用迭代实现了,然后考虑能否写一个递归,对于任意自然数都适用,对于下列代码,只需修改main方法里面判断条件,即可对更多位的自然数进行操作

  • 之前写代码没有注意格式,最近看了阿里的java开发手册,试着写更加具有可读性的代码

  • 在input.nextInt()后,加上input.close(),回收空间
import java.util.Scanner;
public class RecursionSumOfInteger {

    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.println("Input a natural number between 0-1000");
        int number = input.nextInt();
        input.close();
        if(number <= 1000 && number >= 0){
            int result = 0;
            result = remainNumber(number); 
            System.out.println("The sum of " + number + " is " + result);
        }
        else if(number > 1000){
            int resultBeyond = 0;
            resultBeyond = remainNumber(number);
            System.out.println("Input beyond the yield! and the recommended result is " + resultBeyond);
        }    
        else
            System.out.println("Input illegal!");   
    }

    public static int remainNumber(int i){
        int sum = 0;
        if (i <=9 && i >=0)
        return i;
        else{
            sum = i % 10 + remainNumber((i / 10));
        return sum;
        }
    }
}

你可能感兴趣的:(java)