題目描述
將一個字串轉換成一個整數,要求不能使用字串轉換整數的庫函式, 數值為0或者字串不是一個合法的數值則回傳0
思路
逐位轉換,注意邊界值,時間復雜度O(m),空間復雜度O(1),
代碼
public class Solution {
public int StrToInt(String str) {
if(str == null || str.equals("")) return 0;
char[] cs = str.toCharArray();
int ans = 0;
int flag = cs[0] == '-' ? -1 : 1;
for(int i=(cs[0]=='+' || cs[0]=='-')?1:0; i < cs.length; i++){
if(cs[i] < '0' || cs[i] > '9') return 0;
ans = (ans<<3) + (ans<<1) + (cs[i]&0xf);
}
ans *= flag;
if(((ans>>31)&1) == 0 && flag == -1) return 0;
if(((ans>>31)&1) == 1 && flag == 1) return 0;
return ans;
}
}
筆記
檢查是否溢位,可以比較原數字與轉換后數字的補碼符號位,
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/205856.html
標籤:其他
上一篇:leetcode面試題 02.06. 回文鏈表,解題心路
下一篇:陣列中重復的數字
