題目描述
實現atoi這個函數,將一個字符串轉換爲整數。如果沒有合法的整數,返回0。如果整數超出了32位整數的範圍,返回INT_MAX(2147483647)如果是正整數,或者INT_MIN(-2147483648)如果是負整數。
樣例1
輸入: "10"
輸出: 10
樣例2
輸入: "1"
輸出: 1
樣例3
輸入: "123123123123123"
輸出: 2147483647
說明: 因爲 123123123123123 > INT_MAX, 所以我們返回INT_MAX
樣例4
輸入: "1.0"
輸出: 1
說明: 我們只需要轉換第一個有效數字
題解
比起自己刷題,有大神帶着刷肯定更好,專業的算法課程(點擊免費試聽)可以隨問隨答,在最短時間內提高算法水平,應對大廠面試。
public class Solution {
public int atoi(String str) {
// Start typing your Java solution below
// DO NOT write main() function
if(str == null) {
return 0;
}
str = str.trim();
if (str.length() == 0) {
return 0;
}
int sign = 1;
int index = 0;
if (str.charAt(index) == '+') {
index++;
} else if (str.charAt(index) == '-') {
sign = -1;
index++;
}
long num = 0;
for (; index < str.length(); index++) {
if (str.charAt(index) < '0' || str.charAt(index) > '9')
break;
num = num * 10 + (str.charAt(index) - '0');
if (num > Integer.MAX_VALUE ) {
break;
}
}
if (num * sign >= Integer.MAX_VALUE) {
return Integer.MAX_VALUE;
}
if (num * sign <= Integer.MIN_VALUE) {
return Integer.MIN_VALUE;
}
return (int)num * sign;
}
}