String to-Integer-Atoi

Anonymous User
65
Jun 18, 2024

class Solution {
public int myAtoi(String s) {

    // Step 1: Trim leading and trailing whitespaces
    s = s.trim();
	
    // Step 2: Handle empty string after trimming
    if (s.length() == 0) {
        return 0;
    }

    // Step 3: Handle optional sign
    int sign = 1;
    int startIndex = 0;
    if (s.charAt(0) == '-') {
        sign = -1;
        startIndex++;
    } else if (s.charAt(0) == '+') {
        startIndex++;
    }

    // Step 4: Convert characters to integer
    long num = 0;
    for (int i = startIndex; i < s.length(); i++) {
        char c = s.charAt(i);
        if (!Character.isDigit(c)) {
            break;
        }

        num = num * 10 + (c - '0');

        // Step 5: Handle overflow and underflow
        if (num * sign > Integer.MAX_VALUE) {
            return Integer.MAX_VALUE;
        }
        if (num * sign < Integer.MIN_VALUE) {
            return Integer.MIN_VALUE;
        }
    }

    return (int) (num * sign);
}

}

Comments (0)