# Solution by rohitnandi12

• Tip: Always ask questions to the interviewer and clarify about the problem, you can even ask for test cases.

Possible Question for this problem are: ( Let the input string be s )

• what will be the return value on s being empty or only white space or invalid integer
( requirement: return 0 )
• what if s contains white spaces before and after it. ( requirement : trim extra spaces )
• can the integer be negative, and have - or + sign as the first character ( requirement: yes)
• What is the bit size of the Integer ( requirement: 32 bit )
• What if s represents a number greater than 32bit integer range
( requirement: return INT_MAX (2147483647) or INT_MIN (-2147483648) )
• Can the string contain mix of digit and alphabets ( requirement: yes )

Test Cases

Try to create your own test cases.

``````T<Index> = value   // Output
T1 = "       "     // 0
T2 = ""            // 0
T3 = "   +567  "   // +567
T4 = "   -567  "   // -567
T5 = "-567abc89"   // -567
T6 = "abc-567"     // 0
``````

#### Approach #1 Implementation [Accepted]

Intuition

``````An Integer say `6789` can be formed in for steps.
Step1: 6
Step2: 6*10 + 7 = 60 + 7 = 67
Step3: 67*10 + 8 = 670 + 8 = 678
Step4: 678*10 + 9 = 6780 + 9 = 6789
``````

Algorithm

• If str is empty or has only white space return 0
• Check if negative or positive symbol attached
• Iterate to rest of the characters
• If character is not a digit, break and return 0
• If character is a number multiply result with 10 and add the character in hand
• If new Result is out of Integer range, break and return MAX_INT or MIN_INT
• Change result to negative if required
• return the computed result

Java

``````class Solution {
public int myAtoi(String str) {

str = str.trim();
if(str.length()==0)return 0; // if all white space or empty string

int i=0, ans = 0, ch;
boolean isNegative = false;

ch = str.charAt(i);
if(ch=='-' || ch=='+'){
isNegative = ch=='-'?true:false;
i++;
}

for(; i<str.length(); i++){
ch = str.charAt(i);

if(ch<'0' || ch>'9'){
break;
}
if(!isNegative && ans > (Integer.MAX_VALUE - (ch-'0'))/10){
ans = Integer.MAX_VALUE;
break;
}else if(isNegative && ans - 0.1 > (Integer.MAX_VALUE - (ch-'0'))/10){
ans = Integer.MIN_VALUE*-1;
break;
}

ans = ans*10 + (ch-'0');
}

return isNegative?-1*ans:ans;

}
}
``````

Testing

``````T1 = 0
T2 = 0
T3 = 567
T4 = -567
T5 = -567
T6 = 0
``````

Complexity Analysis

• Time complexity : \$\$O(n)\$\$ where n is the length of the input string.

• Space complexity : \$\$O(1)\$\$.

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.