how to find number of digits in a given number in python or C++ (for example : 345 has 3 digits)? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 2

how to find number of digits in a given number in python or C++ (for example : 345 has 3 digits)?

6th Sep 2020, 10:35 AM
Ankit Nainwal
Ankit Nainwal - avatar
7 Answers
+ 3
In python: Loop through the number (I think you might need to convert it to string first) ,and check whether the type is int using type(firstnumber)==int ,if yes, increment a varaible(let assume it is count initialized with value as 0) Edit: you can simply do as the upper solution would take more operations to do len(str(345))
6th Sep 2020, 10:41 AM
Abhay
Abhay - avatar
+ 3
decoder Convert it to string using str() function Then use len() function to count. len(str(377)). #o/p:- 3
6th Sep 2020, 10:43 AM
Ajith
Ajith - avatar
+ 3
In python you can change int to str then store this int variable and make condition for character in this string variable if this character is digital increase a counter : count += 1 .Finally return this counter variable.You can make all this code in a function.
6th Sep 2020, 10:44 AM
HBhZ_C
HBhZ_C - avatar
+ 2
One way is to keep dividing by ten and increase the result from 0 at the same time until the number itself is 0.
6th Sep 2020, 10:44 AM
你知道規則,我也是
你知道規則,我也是 - avatar
+ 1
If you convert to string and count characters, be sure to handle potential for a negative sign or a decimal character. If it is a whole number, then you can determine it mathematically. Find the magnitude by taking the log (base 10) and truncating the result to its integer floor. Then add 1 to get the number of digits. Use absolute value if the number may be negative. Log fails if the input number is zero, however, so make a special case for that. In C++: int num = 345; ndigits = (num ? trunc(log10(abs(num)))+1 : 1); https://code.sololearn.com/cGN8zCE1fPxa/?ref=app
6th Sep 2020, 2:09 PM
Brian
Brian - avatar
+ 1
1. Convert it to string 2. Find its length
8th Sep 2020, 5:23 AM
Satyam Mishra
Satyam Mishra - avatar
0
#In python n=int(input()) Count=0 while n!=0: Reminder=n%10 count=count+1 n=n//10 print(count)
8th Sep 2020, 3:38 AM
HariHaran
HariHaran - avatar