如何高效实现数字数位迭代求和直至得到单个数字?
Hey there! I see you've already nailed the first part—summing the digits of your input number. Now let's extend that logic to keep iterating until we land on a single-digit result. This is actually called the digital root of a number, and we can solve it in two simple, effective ways:
Method 1: Iterative Loop (Follows Your Exact Process)
This approach mirrors the step-by-step calculation you described: we keep summing the digits of the result until it's a single digit. Here's how to tweak your code:
num = input().strip() # Calculate the initial sum of all digits current_sum = sum(map(int, num)) # Keep looping until we get a single-digit number while current_sum >= 10: # Convert the current sum back to a string to split into individual digits current_sum = sum(map(int, str(current_sum))) print(current_sum)
Let's walk through your example (123456):
- First sum:
1+2+3+4+5+6 = 21 - Since 21 isn't a single digit, we sum its digits:
2+1 = 3 - Now we have a single digit, so we print 3.
Method 2: Mathematical Formula (Faster for Large Numbers)
For really big numbers, a loop might feel slow—but there's a mathematical shortcut for digital roots! The rule is:
- If the number is 0, the digital root is 0
- If the number is divisible by 9, the digital root is 9
- Otherwise, it's the remainder when the number is divided by 9
Here's the code for this approach:
num = input().strip() n = int(num) if n == 0: print(0) else: digital_root = 9 if n % 9 == 0 else n % 9 print(digital_root)
Testing with 123456:
123456 ÷ 9leaves a remainder of 3, so the digital root is 3—exactly what you expected!
Both methods work great, but the formula is more efficient for huge numbers since it skips the looping entirely.
内容的提问来源于stack exchange,提问作者Naxocist

