0
"Please help me correct this code."
Note: When finding the sum of the digits until only one digit remains, only integer operations are allowed (no string or list operations). Example Input/Output: Input: 23 Output: 5 Explanation: The sum of the digits of 23 is 2 + 3 = 5, which is a single digit. Input: 24682 Output: 4 Explanation: The sum of the digits of 24682 is 2 + 4 + 6 + 8 + 2 = 22. The sum of the digits of 22 is 2 + 2 = 4, which is a single digit.
8 ответов
+ 2
When writing a number you want to add to another number, add a float(x), with x being the number.
For example: 1 + 3. When i want it to print out 4, not 13, i write print(float(1) + float(3)). This must print out a 4.0 . Hope this helps!
+ 2
def add_(x,s):
if len(x)!=1:
s=sum(x)
x=[]
for i in str(s):
x.append(int(i))
return add_(x,s)
else:
return print(s)
a=int(input("Enter any Integer No. : "))
print()
x=[int(i) for i in str(a)]
add_(x,0)
+ 1
Mohamed Beder Oumar ,
Nice idea. This fixes the errors. Somebody else can put the loop in a loop to keep doing passes until its a single digit.
num = abs(int(input()))
sum = 0
while(num):
sum += num % 10
num //= 10
print(sum)
+ 1
ANKIT CHANDOK ,
Nice recursion. My tweaks:
def add_(x, s):
if len(x) != 1:
s = sum(x)
x = []
for i in str(s):
x.append(int(i))
return add_(x, s)
else:
return s
a = input("Enter a non-negative integer: ")
print(a)
x = [int(i) for i in a]
print(add_(x, 0))
https://sololearn.com/compiler-playground/cRtsxtvc3dQ7/?ref=app
+ 1
https://sololearn.com/compiler-playground/cCu3WhjT5C1l/?ref=app
0
num = ?
sum=0
While(X):
sum += num%10
num //= 10
print(sum)
0
Hii