Solved

Itoa algorithm?

Posted on 1997-10-15
2
1,080 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

Free Tool: Site Down Detector

Helpful to verify reports of your own downtime, or to double check a downed website you are trying to access.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Unlike C#, C++ doesn't have native support for sealing classes (so they cannot be sub-classed). At the cost of a virtual base class pointer it is possible to implement a pseudo sealing mechanism The trick is to virtually inherit from a base class…
This article shows you how to optimize memory allocations in C++ using placement new. Applicable especially to usecases dealing with creation of large number of objects. A brief on problem: Lets take example problem for simplicity: - I have a G…
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++.

839 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