digitSum=0
n=222222222222222222222222222222
while n!=0:
digitSum=digitSum+(n%10)
n=int(n/10)
print(digitSum)
The output should be 60, whereas the output is 86.
digitSum=0
n=222222222222222222222222222222
while n!=0:
digitSum=digitSum+(n%10)
n=int(n/10)
print(digitSum)
The output should be 60, whereas the output is 86.
This should work too.
digitSum=0
n=222222222222222222222222222222
stringValue = str(n)
length = len(stringValue)
digitSum = length * int(stringValue[0])
print(digitSum)
Use a // b
for integer division, not int(a / b)
.
On the first iteration of your loop, your code is effectively doing int(222222222222222222222222222222 / 10)
. This results in a floating point value which you expect to be 22222222222222222222222222222.2
but in reality is 22222222222222223739180810240.0
due to limitations in floating point precision. This value propagates to the next iteration of your algorithm, where it obviously causes your wrong answer.
On the other hand //
in Python performs integer division, which results in the truncated result you want. Because Python has unlimited integer range, this will work correctly even with very large numbers. So 222222222222222222222222222222 // 10
correctly results in the same number with the last digit removed.