Leetcode 8 String to Integer (atoi) Solution in Java | Hindi Coding Community

0

 


Implement the myAtoi(string s) function, which converts a string to a 32-bit signed integer (similar to C/C++'s atoi function).

The algorithm for myAtoi(string s) is as follows:

  1. Read in and ignore any leading whitespace.
  2. Check if the next character (if not already at the end of the string) is '-' or '+'. Read this character in if it is either. This determines if the final result is negative or positive respectively. Assume the result is positive if neither is present.
  3. Read in next the characters until the next non-digit character or the end of the input is reached. The rest of the string is ignored.
  4. Convert these digits into an integer (i.e. "123" -> 123"0032" -> 32). If no digits were read, then the integer is 0. Change the sign as necessary (from step 2).
  5. If the integer is out of the 32-bit signed integer range [-231, 231 - 1], then clamp the integer so that it remains in the range. Specifically, integers less than -231 should be clamped to -231, and integers greater than 231 - 1 should be clamped to 231 - 1.
  6. Return the integer as the final result.
class Solution {
public int myAtoi(String s) {
s = s.trim();
if (s.length() < 1)
return 0;

int sign = 1;
int i =0;
if(s.charAt(0) == '-') {
sign = -1;
i = 1;
} else if(s.charAt(0) == '+') {
i = 1;
}
int ans = 0;
for (; i < s.length(); i++) {
int num = s.charAt(i) - 48;

if ((num >= 0 && num <= 9)) {
if (sign > 0) {
if (ans <= Integer.MAX_VALUE / 10
&& ((ans * 10) < Integer.MAX_VALUE - num)) {
ans = ans * 10 + num;
} else {
return Integer.MAX_VALUE;
}
}

if (sign < 0) {
if (ans * sign >= Integer.MIN_VALUE / 10
&& ((ans * 10) * sign > Integer.MIN_VALUE + num)) {
ans = ans * 10 + num;
} else {
return Integer.MIN_VALUE;
}
}

} else {
break;
}
}
return ans * sign;

}
}


Post a Comment

0Comments
Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Learn More
Accept !