leetcode 8.字串轉整數(atoi)
阿新 • • 發佈:2019-01-24
思路:先排除掉字串中的空格,然後如果第一個非空字元是整好或負號則記錄下來,再將前面所有連續數字轉換成整數即可。
class Solution { public: int myAtoi(string str) { long temp=0; int s=0; int i=0; while(str[i]==' ') i++; if(str[i]=='+') i++; else if(str[i]=='-'){ i++; s=1; } while(str[i]>='0'&&str[i]<='9'){ temp=temp*10+(str[i]-'0'); if(temp>2147483646&&s==0) { return 2147483647; } if(temp>2147483647&&s==1) return -2147483648; i++; } int res=temp; return s?-res:res; } };