牛客:把字串轉成整數
阿新 • • 發佈:2018-12-04
題目描述:
將一個字串轉換成一個整數(實現Integer.valueOf(string)的功能,但是string不符合數字要求時返回0),要求不能使用字串轉換整數的庫函式。 數值為0或者字串不是一個合法的數值則返回0。
輸入描述:
輸入一個字串,包括數字母符號,可以為空。
輸出描述:
如果是合法的數值表達則返回該數字,否則返回0。
C++程式碼:
class Solution { public: int StrToInt(string str) { int size = str.size(); if(size == 0) return 0; int index = 0; int lebal = 1; if(str[0] == '+') { lebal = 1; ++index; } if(str[0] == '-') { lebal = -1; ++index; } int num = 0; int tmp = 1; while(index < size) { if(str[index] < '0' || str[index] > '9') { return 0; break; } tmp = str[index]-'0'; for(int i = 0;i < size-index-1;++i) { tmp *= 10; } num += tmp; ++index; } return lebal*num; } };