題目:將一個字符串轉(zhuǎn)換成一個整數(shù)(實現(xiàn)Integer.valueOf(string)的功能,但是string不符合數(shù)字要求時返回0)卷玉,要求不能使用字符串轉(zhuǎn)換整數(shù)的庫函數(shù)哨颂。 數(shù)值為0或者字符串不是一個合法的數(shù)值則返回0。
練習(xí)地址
https://www.nowcoder.com/practice/1277c681251b4372bdef344468e4f26e
https://leetcode-cn.com/problems/ba-zi-fu-chuan-zhuan-huan-cheng-zheng-shu-lcof/
參考答案
public class Solution {
public int StrToInt(String str) {
if (str == null || str.length() == 0) {
return 0;
}
int num = 0, index = 0;
boolean minus = false;
if (str.charAt(0) == '+') {
index++;
} else if (str.charAt(0) == '-') {
minus = true;
index++;
}
while (index < str.length()) {
char digit = str.charAt(index++);
if (digit >= '0' && digit <= '9') {
num = num * 10 + digit - '0';
} else {
return 0;
}
}
return minus ? -num : num;
}
}
復(fù)雜度分析
- 時間復(fù)雜度:O(n)相种。
- 空間復(fù)雜度:O(1)威恼。