# EPI 6.1 | Integer Convert Strings and Integers

## Problem

Implement two functions: intToString() and stringToInt().

Example:

## Analysis

### intToString()

Also refer to 7. Reverse Integer.

Let’s first analyze the incorrect version. Here are two tiny errors in the following code.

The basic idea is to record the negative sign, sum up from LSD to MSD, and finally reverse the whole string.

Error #1:

When x == 0, the StringBuilder remains empty. Two solutions:

• Use do-while.
• Add if (x == 0) return 0; special case handler.

Error #2:

• Why can’t we do x = Math.abs(x) at the beginning?
• Why should we use x != 0 rather than x > 0?

Consider the case when x = -2147483648, which is Integer.MIN_VALUE. If we extract the numeric part and process it as a positive number, it would overflows.

Solutions:

• Do Math.abs inside while.

• Use a long integer to store x.

Time: $O(N)$
Space: $O(1)$

### stringToInt()

Assume the input is valid. It can be extended if s could be a very large number, then we should use long type.

Remember String in Java is immutable.

Time: $O(N)$
Space: $O(1)$

Comment
Junhao Wang
a software engineering cat