The function digits, in the while loop – while (n > 0) returns 325 326 327 and 1 as the count value and if I use while (n > 1) it returns the correct number count. Any logical reason for this behavior?
JavaScript
x
14
14
1
def digits(n):
2
count = 0
3
if n == 0:
4
return 1
5
while (n > 0):
6
count += 1
7
n = n / 10
8
return count
9
10
print(digits(25)) # Should print 2
11
print(digits(144)) # Should print 3
12
print(digits(1000)) # Should print 4
13
print(digits(0)) # Should print 1
14
Advertisement
Answer
There is a difference between /
and //
.
/
does the normal division given an accurate answer upto 15 decimal places in python. However, //
is the floor division method where only the quotient of the division is returned.
try to replace:
JavaScript
1
2
1
n = n / 10
2
with this:
JavaScript
1
2
1
n = n // 10
2