How to calculate the digits of a positive integer?
By Angsuman Chakraborty, Gaea News NetworkSunday, January 25, 2004
I just came across the need to calculate the digits of a number. It sounds trivial as we can see the digits & count them easily.
The challenge is how to find them (with least effort) computationally?
Solution:
1 + (int) (Math.log(i) / base10)
where base10 = Math.log(10)
|
Paul J |
|
Kevin |
September 17, 2009: 1:09 am
It doesnt seem to work when I enter a 7 digit number, I get a cound of 6. It works on 6 digits and 8 digits but not 7. Probably more errors with other values as well.. |
|
July 23, 2009: 8:53 pm
@Min the issue with this approach is you have to explicitly set the bounds. This is fine for base 10, but what about base 2? One can represent a pretty long binary number in a “long” datatype. @Absar String operations are much expensive than numerical operations. Also, this does not take into account other bases (though it could, by using a STRING->NBASE function). |
|
January 25, 2004: 6:16 am
Hmm. Did a search and found this. http://mindprod.com/jgloss/widthindigits.html /** |
sonnykwe