public static int sumDigits(long n)
For example, sumDigits(234) returns 9 (2+3+4). Use a loop to repeatedly extract and remove the digit until all the digits are extracted. Write a test program thar prompts the user to enter an inter an integer and displays the sum of all its digits.
import java.util.Scanner; public class C1 { public static void main(String[] args) { Scanner input = new Scanner(System.in); //提示使用者輸入整數 System.out.println("請輸入整數:"); int number = input.nextInt(); //呼叫 sumDigits 並印出答案 System.out.println(sumDigits(number)); } public static int sumDigits(int num ) { int sum = 0; while( num > 0) { int a = num % 10; //將整數拆解成1位1位 int b = num / 10; //拆掉一位後剩下的數字 sum = sum + a ; // 將拆解後的數字加入總和 num = b ; } return sum; //回傳結果 } }
沒有留言:
張貼留言