
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Find Sum of Digits Until One Digit Number in Python
Suppose we have a positive number n, we will add all of its digits to get a new number. Now repeat this operation until it is less than 10.
So, if the input is like 9625, then the output will be 4.
To solve this, we will follow these steps −
- Define a method solve(), this will take n
- if n < 10, then
- return n
- s := 0
- l := the floor of (log(n) base 10 + 1)
- while l > 0, do
- s := s + (n mod 10)
- n := quotient of n / 10
- l := l - 1
- return solve(s)
Let us see the following implementation to get better understanding −
Example
import math class Solution: def solve(self, n): if n < 10: return n s = 0 l = math.floor(math.log(n, 10) + 1) while l > 0: s += n % 10 n //= 10 l -= 1 return self.solve(s) ob = Solution() print(ob.solve(9625))
Input
9625
Output
4
Advertisements