Problem C - 2 the 9s
Time Limit: 1 second
Time Limit: 1 second
Introduction to the problem
A well-known trick to know if an integer N is a multiple of nine is to compute the sum S of its digits. If S is a multiple of nine, then so is N. This is a recursive test, and the depth of the recursion needed to obtain the answer on N is called the 9-degree of N.
Your job is, given a positive number N, determine if it is a multiple of nine and,if it is, its 9-degree.
Description of the input
The input is a file such that each line contains a positive number. A line containing the number 0 is the end of the input. The given numbers can contain up to 1000 digits.
Description of the output
The output of the program shall indicate, for each input number, if it is a multiple of nine, and in case it is, the value of its nine-degree. See the sample output for an example of the expected formatting of the output.
Sample input:
999999999999999999999
9
9999999999999999999999999999998
0
Sample output
999999999999999999999 is a multiple of 9 and has 9-degree 3.
9 is a multiple of 9 and has 9-degree 1.
9999999999999999999999999999998 is not a multiple of 9.
解法: 每次把所有位數加總 如果是9的倍數就往下遞迴
import java.util.Scanner;
public class UVA10922 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while (sc.hasNext()) {
String str = sc.nextLine();
if (str.equals("0"))
break;
System.out.print(str + " is ");
int num = 0, t_num = 0, count = 0;
for (int i = 0; i < str.length(); i++)
num += Integer.parseInt(str.substring(i, i + 1));
if (num % 9 == 0)
count++;
while (num % 9 == 0 && num > 9) {
t_num = num;
count++;
num = 0;
while (t_num > 0) {
num += t_num % 10;
t_num /= 10;
}
}
System.out.println(num == 9 ? "a multiple of 9 and has 9-degree "
+ count + "." : "not a multiple of 9.");
}
sc.close();
}
}
留言
張貼留言