Code Logo

Convert with Integer.parseInt()

Published at25 Jul 2026
Java OOP Easy 0 views
Like0

Write a Java function that takes a string representation of an integer, parses it to int using Integer.parseInt(), adds 1 to it, and converts the result back to a string using Integer.toString().

Integer.parseInt() is a static method that converts a String to a primitive int. It throws NumberFormatException if the string does not contain a parsable integer. Integer.toString() converts an int to its String representation. These methods are the standard way to convert between integers and strings in Java.

The Integer class is part of Java's wrapper class family (Boolean, Byte, Short, Integer, Long, Float, Double). Each wrapper class provides parseXxx() and toString() methods for conversion. Java also provides valueOf() methods that return wrapper objects, which can be more memory-efficient due to caching for common values (-128 to 127).

Time complexity is O(n) where n is the number of digits in the string. Space complexity is O(n) for the result string. Integer.parseInt processes each character digit-by-digit, multiplying the accumulator by 10 and adding the digit value.

Edge cases include negative numbers (handled by the minus sign), leading zeros (allowed), very large numbers exceeding Integer.MAX_VALUE (throws NumberFormatException), and invalid characters (also throws NumberFormatException).

Example Input & Output

Example 1
Input
"-1"
Output
0
Explanation

-1 + 1 = 0

Example 2
Input
"41"
Output
42
Explanation

41 + 1 = 42

Example 3
Input
"99"
Output
100
Explanation

99 + 1 = 100

Example 4
Input
"10"
Output
11
Explanation

10 + 1 = 11

Example 5
Input
"0"
Output
1
Explanation

0 + 1 = 1

Algorithm Flow

Recommendation Algorithm Flow for Convert with Integer.parseInt()
Recommendation Algorithm Flow for Convert with Integer.parseInt()

Solution Approach

class Solution {
    public String solution(String s) {
        int num = Integer.parseInt(s);
        return Integer.toString(num + 1);
    }
}

Best Answers

java - Approach 1
class Solution {
    public String solution(String s) {
        int num = Integer.parseInt(s);
        return Integer.toString(num + 1);
    }
}