Reputation: 21
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?
def digits(n):
count = 0
if n == 0:
return 1
while (n > 0):
count += 1
n = n / 10
return count
print(digits(25)) # Should print 2
print(digits(144)) # Should print 3
print(digits(1000)) # Should print 4
print(digits(0)) # Should print 1
Upvotes: 0
Views: 1671
Reputation: 37
Correct Code
def digits(n):
count = 0
if n == 0:
return 1
while (n > 0):
count += 1
n = n//10
return count
print(digits(25)) # Should print 2
print(digits(144)) # Should print 3
print(digits(1000)) # Should print 4
print(digits(0)) # Should print 1
Logic being used We're using floor division instead of normal one because normal one will make the loop take very much time but return nothing so here, we'll use floor division until n gets smaller than 10 till then the count will get increasing by 1
For ex: We take 25 as an input
25 // 10 = 2 count gets 1
2 // 10 = inputs gets smaller than zero count increases by 1 until condition is satisfied so now the count is 2
Hope this helps :)
Upvotes: 1
Reputation: 480
If you divide something by 10 it will always be larger than 0, a quicker way would be:
def digits(n):
return len(str(n))
Upvotes: 0
Reputation:
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:
n = n / 10
with this:
n = n // 10
Upvotes: 1