
Description
Given a non-negative integer num, repeatedly add all its digits until the result has only one digit.
For example:
Given num = 38, the process is like: 3 + 8 = 11, 1 + 1 = 2. Since 2 has only one digit, return it.
Solution
有一种解法是利用循环完成:
|
|
另一种解法,利用mod,小学的时候学过判断一个数能不能被9整除,直接将各位的数相加判断能不能被9整除,这个与本题有异曲同工之处,所以可以利用mod9的余数来表示。因为各个数相加不可能等于0,所以可以如下:
|
|




近期评论