編寫一個方法,計算一個整數各位數字之和

代碼:
package com.im;

import java.util.Scanner;

public class Demo62 {

public static void main(String[] args) {
    // TODO Auto-generated method stub

    Scanner input = new Scanner(System.in);
    System.out.print("請輸入一個整數:");

    long n = input.nextLong();

    System.out.println(sumDigits(n));

}

public static int sumDigits(long n){ //計算一個整數各位數字之和

    int total = 0;  //各位數字之和
    int count = 0;

    count = getDigitOfNumber(n);

    for(int i=1; i<=count; i++){
        long v = n%10; //獲得數字
        total += v; //數字之和
        n /= 10;  //去除位數
    }
    return total;
}
public static int getDigitOfNumber(long n){ //獲取輸入整數的位數
    int count = 0;
    while(n>0){  
        n = n/10;
        count++;
    }
    return count;
}

}

這裏寫圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章