用java求一个整数各位数字之和

/*
 * 用java求一个整数各位数字之和
 */
public class Test02 {

    public static void main(String[] args) {
        System.out.println(Test02.sumDig(23865));
        System.out.println(Test02.sumDig2(23965));
    }

    public static int sumDig(int n) {
        int sum = 0;
        if (n >= 10) {
            sum += n % 10;
            sum += sumDig(n / 10);
        } else
            sum += n;
        return sum;
    }

    public static int sumDig2(int n) {
        int sum = 0;
        while (n >= 10) {
            sum += n % 10;
            n /= 10;
        }
        sum += n;
        return sum;
    }
}

 

posted on 2017-11-03 19:59    阅读(9007)  评论(0编辑  收藏  举报