Programming Practice: Integer To String

This is a new section we are going to start. We will be talking about how to solve some typical and commonly asked (in interviews) programming questions. To start off, this one is a relatively simple one.

Problem: Given an integer value, convert it to its string representation.

Examples:
Input: 127, Output: “127″
Input: -123, Output: “-123″

Algorithm:
1. Determine if the number is negative. If yes, multiply by -1 to make it positive. Lets call this ‘n’.
2. Compute n%10 (remainder of the division). This is the value of theĀ  current digit, starting off with the least significant one. Store this digit in a temp array location.
3. Divide n by 10. Assign this to n.
4. Repeat steps 2 and 3 till n becomes 0.
5. At this point the output could potentially contain the reversed string representation. We can go through this output to create the output in the correct order.

Java Code:

There are other ways of solving this problem which would not require reversing the output in the end. This is just one possible solution.

Advertisement

One Response to Programming Practice: Integer To String

  1. Pingback: Programming Practice: String To Integer « Technical Bhaigiri

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s