8504. Sum of Digits
Posted tangxlblog
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了8504. Sum of Digits相关的知识,希望对你有一定的参考价值。
Sum of Digits
Having watched the last Harry Potter film, little Gerald also decided to practice magic. He found in his father‘s magical book a spell that turns any number in the sum of its digits. At the moment Gerald learned that, he came across a number n. How many times can Gerald put a spell on it until the number becomes one-digit?
The first line contains the only integer n (0≤n≤101000000). It is guaranteed that n doesn‘t contain any leading zeroes.
Print the number of times a number can be replaced by the sum of its digits until it only contains one digit.
0
0
10
1
991
3
In the first sample the number already is one-digit ? Herald can‘t cast a spell.
The second test contains number 10. After one casting of a spell it becomes 1, and here the process is completed. Thus, Gerald can only cast the spell once.
The third test contains number 991. As one casts a spell the following transformations take place: 991→19→10→1. After three transformations the number becomes one-digit.
说明:此题就是不断地对数字按位累加,直到这些数字之和变为个位数为止,又由于输入的数字可能会很大,所以应该使用字符串接收,然后将该字符串转为字符数组,字符数组的每一个元素都是数字,对数字累加,然后将累加的和再更新到该字符数组,直到此字符数组的长度为1(也就是这些数字之和变为个位数)。输出的结果为:上述步骤的步数。
import java.util.Scanner; public class Test8504 { public static void main(String[] args) { Scanner sc = new Scanner(System.in); String str = sc.nextLine(); char[] chArr = str.toCharArray(); int result = 0; while (chArr.length > 1) { int num = 0; for (char ch : chArr) { num += (int) ch - 48; } str = Integer.toString(num); chArr = str.toCharArray(); result++; } System.out.println(result); sc.close(); } }
以上是关于8504. Sum of Digits的主要内容,如果未能解决你的问题,请参考以下文章
CodeForces 489C Given Length and Sum of Digits...
[codewars_python]Sum of Digits / Digital Root
C. Given Length and Sum of Digits... (贪心)
C. Given Length and Sum of Digits...