Count Number of Digits

1 min read

Naive:
Time Complexity: O(log₁₀(n))
Space Complexity: O(1)
def countDigits(n:int) -> int:
int res = 0
while (x>0):
x = x//10
res += 1
return res
Recursive Way:
Time Complexity: O(log₁₀(n))
Space Complexity: O(log₁₀(n))
def countDigits(n:int) -> int:
if n//10==0:
return 1
return 1 + countDigits(n//10)
Best Way:
Time Complexity: O(log₁₀(n))
Space Complexity: O(log₁₀(n)) — due to string conversion
def countDigits(n: int) -> int:
return len(str(n))
0
Subscribe to my newsletter
Read articles from Divyesh Vishwakarma directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by

Divyesh Vishwakarma
Divyesh Vishwakarma
Extremely enthusiastic in the field of software and web development, Divyesh is continuously learning and gathering knowledge to remain abreast. Solving problems using Python(3) is intriguing for him so it's his niche currently working in Zeus Learning | MotiDivya