Don't know It's right place to ask this or not. But I was feeling completely stuck. Couldn't find better way to solve it.
I am newbie in competitive Programming. I was solving Repeated sum of digits problem Here is The Question.
Given an integer N, recursively sum digits of N until we get a single digit.
Example:-
Input:
2
123
9999
Output:-
6
9
Here is my code:-
def sum(inp):
if type(inp) == int:
if len(str(inp)) <= 1:
return inp
else:
a = list(str(inp))
while len(a) > 1:
b = 0
for i in a:
b+= int(i)
a = list(str(b))
return b
t = int(raw_input())
for i in range(0,t):
print sum(i)
While submitting it gave My following error:-
Wrong !! The first test case where your code failed:
Input:
42
Its Correct output is:
6
And Your Output is:
0
However When I tested my code personally using 42 It's perfectly gives me correct Output 6.
Here is the link of question:- Repeated sum of digits Error
You have not implemented the code properly. You are iterating over i from 0 to t. Why?? The methodology goes as follows:
N = 12345
Calculate the sum of digits(1+2+3+4+5 = 15).
Check if it is less than 10. If so, then the current sum is the answer.. If not.. follow the same procedure by setting N = 15
Here is the code:
def sum(inp):
while inp > 9:
num = inp
s = 0
while num > 0:
s = s + num%10
num = num/10
inp = s
return inp
t = int(raw_input())
for i in range(t):
n = int(raw_input())
print sum(n)
Edit: I think you are iterating till t because you have considered t to be the number of testcases. So, inside the for loop, you should take another input for N for each of the testcase. [This is based on the input and output that you have provided in the question]
Edit-2: I have changed the code a bit. The question asks us to find the repeated sum of t numbers. For that, I have added a loop where we input a number n corresponding to each testcase and find its repeated sum.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With