Problem Statement
The challenge is to implement your own method for converting a string to an integer without using any built-in methods. This is a very common question in coding interviews. The string may represent a positive or negative integer, and you should be able to handle both.
For example:
- Input: “123”
Output: 123 - Input: “-123”
Output: -123 - Input: “0”
Output: 0
Note: You can assume that the string will always be a valid integer string, i.e., it won’t contain any alphabetical characters or other invalid symbols like ‘#’, ‘@’, etc.
Solution
Approach:
The intuition behind the solution approach is as follows:
- Decimal Place Value: The key insight is understanding how numbers work in the decimal system. Each digit in a number has a place value based on its position. For instance, in “123”, the digit ‘1’ represents ‘100’, ‘2’ represents ’20’, and ‘3’ represents ‘3’.
- Character to Integer Mapping: In ASCII, digits ‘0’ to ‘9’ are contiguous. So, the integer value of a digit character can be obtained by subtracting the ASCII value of ‘0’ from it. This gives us a way to convert a character to its corresponding integer digit.
- Building the Number: Starting from the leftmost digit, each subsequent digit adds to the number but also pushes the existing digits to a higher place value (by a factor of 10). For example, to convert “123” to an integer:
- Start with
1
- Multiply by
10
, then add2
to get12
- Multiply by
10
, then add3
to get123
- Start with
- Negative Numbers: If the string starts with a negative sign, we remember this with a boolean flag (
isNegative
). At the end of the conversion, we negate the number if this flag is true.
Java code:
Here’s the complete Java code to solve the problem.
public class Main {
public static void main(String[] args) {
System.out.println(strToInt("123")); // Output should be 123
System.out.println(strToInt("-123")); // Output should be -123
System.out.println(strToInt("0")); // Output should be 0
}
public static int strToInt(String str) {
int result = 0; // Initialize result
boolean isNegative = false; // Initialize isNegative flag as false
// Check for negative sign; if it's there, set the isNegative flag
if (str.charAt(0) == '-') {
isNegative = true;
}
// Loop through the string, skipping the negative sign if necessary
for (int i = (isNegative ? 1 : 0); i < str.length(); i++) {
// Convert each character to its integer value by subtracting '0'
int digit = str.charAt(i) - '0';
// Add the digit to the result after shifting the current value
result = result * 10 + digit;
}
// If the original string represented a negative number, negate the result
if (isNegative) {
result = -result;
}
return result;
}
}
We systematically convert each character to its integer representation, build the number by considering the place value of each digit, and handle the case where the number is negative.
Some interviewer might present the variation of this problem which says that the String might contain leading or trailing white-space characters. In that case, you might have to trim those white-space character before applying the logic.
If you found this guide helpful, please share it with others and spread the knowledge!