![]() |
counting digits
Hey,
im writing some code for padding files. Im wondering how i can count the number of digits in an integer... i.e. :
int a = 232;a would have 3 digits, b would have 4 digits, c would have 2 and d would have 1 digit. i've looked all over - all i can find is bitwise stuff - thats not what i want - the number of set bits is not always the same as the number of digits in the integer... hope someone can help! thanks! :D |
Well you have one obvious option which would be convert to a string and count the characters (possibly accounting for leading zeros depending on your task).
Another option might be to test the int against being less than 10, 100, 1000, etc. The max size for a int will mean you won't have to perform countless comparisons. Finally you could look into log's, particularly log10 of the int. |
Hey Eoin,
Thanks for the quick reply! Can you explain the logs a bit more please? Thanks! |
You can divide it by ten until it reaches 0. Like :
:
213 / 10 = 21So you have 3 numbers. |
hey sweet!
ok so obviously using log10 - i would have to use the ceiling function? for example, say our integer is 235, log10 returns 2.37 - and there are actually 3 numbers in the integer, so use celing(2.37) to get 3... that right? |
ok so this works:
:
//number of digitsbut lots of warnings! :/ thanks guys! |
I tried in the windows calculator log555 and the result is 2.744etc. So i guess this was not what eoin ment.
|
I have a problem with overkilling the simple things I guess... So I won't kill all of your fun, I'll leave the leading zero issue up to you to solve (if there is even a potential for it to be a problem) :)
:
#include <iostream> |
Sorry if this question seems stupid but why do you have to write this :
:
std::cin >> y; |
Hi pegasus001, that result is perfectly ok. log555 = 2.744 implies 10^2.744 = 555. It's just a convenient fact that after rounding up the answer gives you the number of digits.
So for example log_2(x) {here I'm saying log to the base b of x) gives you the number of binary digits which would be necessary to hold x. rvm, the warnings are because log10 take and returns a float or double. So you should specify the cast manually and ideally account for when there would be an overflow. Boost.numeric_cast can do this nicely. P.S. a solution based on pegasus' suggestion of dividing by ten would probably be the most optimal as the log functions are very expensive. |
| All times are GMT -5. The time now is 2:23 AM. |
Powered by vBulletin® Version 3.7.0, Copyright ©2000 - 2008, Jelsoft Enterprises Ltd.
Copyright ©2007 DaniWeb® LLC