https://github.com/emahtab/string-to-integer-atoi
https://github.com/emahtab/string-to-integer-atoi
leetcode problem-solving string-to-number
Last synced: about 2 months ago
JSON representation
- Host: GitHub
- URL: https://github.com/emahtab/string-to-integer-atoi
- Owner: eMahtab
- Created: 2020-07-05T06:09:45.000Z (over 5 years ago)
- Default Branch: master
- Last Pushed: 2020-07-05T06:12:01.000Z (over 5 years ago)
- Last Synced: 2025-06-04T23:30:01.706Z (10 months ago)
- Topics: leetcode, problem-solving, string-to-number
- Homepage:
- Size: 1.95 KB
- Stars: 1
- Watchers: 1
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
# Sring to integer atoi
## https://leetcode.com/problems/string-to-integer-atoi
# Implementation :
```java
class Solution {
public int myAtoi(String str) {
if (str == null) return 0;
str = str.trim();
if (str.length() == 0) return 0;
char firstChar = str.charAt(0);
int sign = 1, start = 0, len = str.length();
long sum = 0;
if (firstChar == '+') {
sign = 1;
start++;
} else if (firstChar == '-') {
sign = -1;
start++;
}
for (int i = start; i < len; i++) {
if (!Character.isDigit(str.charAt(i)))
return (int) sum * sign;
sum = sum * 10 + str.charAt(i) - '0';
if (sign == 1 && sum > Integer.MAX_VALUE)
return Integer.MAX_VALUE;
if (sign == -1 && (-1) * sum < Integer.MIN_VALUE)
return Integer.MIN_VALUE;
}
return (int) sum * sign;
}
}
```