Solved

Itoa algorithm?

Posted on 1997-10-15
2
1,070 Views
Last Modified: 2008-03-03
I was wondering how you could (in c/c++ or any language) take an integer like 12345 and convert it into the string "12345" like the C function "Itoa" does.  It would be great if someone could give me step by step instructions or point me to somewhere on the web.  I couldn't find the algorithm myself.
0
Comment
Question by:tdiamond
2 Comments
 
LVL 15

Accepted Solution

by:
Tommy Hui earned 100 total points
ID: 1171550
The basic algorithm is to take the number and divide it by 10. That gives you two components: quotient and remainder. The remainder is the number between 0 and 9 that you can convert a character by adding it to '0'. Repeat until the quotient is 0.

The only tricky part is that as you keep doing this, the remainder is given in backward order.

For example, let's use 12345.

  12345 / 10 = 1234
  12345 % 10 = 5       (% is modulus operator, gives remainder)

  1234 / 10 = 123
  1234 % 10 = 4

  123 / 10 = 12
  123 % 10 = 3

  12 / 10 = 1
  12 % 10 = 2

  1 / 10 = 0
  1 % 10 = 1


0
 

Author Comment

by:tdiamond
ID: 1171551
That is exactly what I needed!  Thank you VERY much.
0

Featured Post

What Security Threats Are You Missing?

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

Join & Write a Comment

  Included as part of the C++ Standard Template Library (STL) is a collection of generic containers. Each of these containers serves a different purpose and has different pros and cons. It is often difficult to decide which container to use and …
C++ Properties One feature missing from standard C++ that you will find in many other Object Oriented Programming languages is something called a Property (http://www.experts-exchange.com/Programming/Languages/CPP/A_3912-Object-Properties-in-C.ht…
The viewer will learn how to user default arguments when defining functions. This method of defining functions will be contrasted with the non-default-argument of defining functions.
The viewer will learn how to clear a vector as well as how to detect empty vectors in C++.

760 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

17 Experts available now in Live!

Get 1:1 Help Now