Jump to content
  • Advertisement
Sign in to follow this  
Nanook

number of diggits in a integer

This topic is 4311 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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.. :/

Share this post


Link to post
Share on other sites
Advertisement
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

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
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?

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!