number of diggits in a integer
How do I find the number of digits in a integer??
like:
1 = 1
10 = 2
100 = 3
I tried with i.size() but that didnt work.. :/
Quote:Original post by Nice Coder
for(int i = 0; x > 9; x /= 10, i++);
Would that work?
i will be off by one and not accesible outside the scope of the for loop.
but either way the important thing, Nanook, is that you be able to explain to your teacher why it works...
If it's a homework assignment then try thinking about it for a while. It wouldn't have been assigned if you didn't have the tools to solve it.
-me
Depends on how the number is represented. Decimal,hex,bin,octal or others system could produce different numbers of digits.
Lets take the number 123d in decimal:
-123d in decimal(123) and has 3 digits,
-123d in hex(7Bh) has 2 digits,
-123d in binary(1111011b) has 7 digits
-123d in octal(173o) has 3 digits.
Lets take the number 123d in decimal:
-123d in decimal(123) and has 3 digits,
-123d in hex(7Bh) has 2 digits,
-123d in binary(1111011b) has 7 digits
-123d in octal(173o) has 3 digits.
Quote:Original post by Palidine
i will be off by one and not accesible outside the scope of the for loop.
Not to mention that it's horribly inefficient to use a loop to do something for which a simple formula exists.
The best way to do this is to convert the number to a string and find the length of the string.
(just kidding)
(just kidding)
Quote:Original post by deathkrush
The best way to do this is to convert the number to a string and find the length of the string.
(just kidding)
hum.. why not?
Quote:Original post by deathkrush
The best way to do this is to convert the number to a string and find the length of the string.
(just kidding)
:)
Ever read The Daily WTF? It's amazing how often the "convert to string" approach is taken in real-world applications by programmers who should know better.
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement