转换字符串到整数
实现atoi这个函数,将一个字符串转换为整数。如果没有合法的整数,返回0。如果整数超出了32位整数的范围,返回INT_MAX(2147483647)如果是正整数,或者INT_MIN(-2147483648)如果是负整数。
样例
"10" =>10
"-1" => -1
"123123123123123" => 2147483647
"1.0" => 1
1 class Solution { 2 public: 3 /** 4 * @param str: A string 5 * @return An integer 6 */ 7 int atoi(string str) { 8 // write your code here 9 str = eraseSpace(str); 10 int size=str.size(); 11 12 if(size <= 0) 13 return 0; 14 15 if(str[0]<=‘9‘ && str[0]>=‘0‘) { 16 int num=str[0]-‘0‘, i, dec=str[0]-‘0‘; 17 for(i=1; i<size; i++) { 18 if(str[i]<=‘9‘ && str[i]>=‘0‘) { 19 dec = num; 20 num = num * 10; 21 if(isCrossBorder(num, dec)) 22 return 2147483647; 23 24 dec = num; 25 num += str[i]-‘0‘; 26 if(isCrossBorder(num, dec)) 27 return 2147483647; 28 } 29 else { 30 return num; 31 } 32 } 33 return num; 34 } 35 else if(str[0] == ‘+‘) { 36 int num=0, i, dec=0; 37 for(i=1; i<size; i++) { 38 if(str[i]<=‘9‘ && str[i]>=‘0‘) { 39 dec = num; 40 num = num * 10; 41 if(isCrossBorder(num, dec)) 42 return 2147483647; 43 44 dec = num; 45 num += str[i]-‘0‘; 46 if(isCrossBorder(num, dec)) 47 return 2147483647; 48 } 49 else { 50 return num; 51 } 52 } 53 return num; 54 } 55 else if(str[0] == ‘-‘) { 56 int num=0, i, dec=0; 57 for(i=1; i<size; i++) { 58 if(str[i]<=‘9‘ && str[i]>=‘0‘) { 59 dec = num; 60 num = num * 10; 61 if(isCrossBorder(num, dec)) 62 return -2147483648; 63 64 dec = num; 65 num += str[i]-‘0‘; 66 if(isCrossBorder(num, dec)) 67 return -2147483648; 68 } 69 else { 70 return num*-1; 71 } 72 } 73 return num*-1; 74 } 75 else { 76 return 0; 77 } 78 } 79 80 bool isCrossBorder(int num1, int num2) { 81 if(num1 < num2) 82 return true; 83 return false; 84 } 85 86 string eraseSpace(string str) { 87 int size=str.size(),i=0,mark=0; 88 string result; 89 90 for(i=0; i<size; i++) { 91 if(str[i]==‘ ‘ && mark==0) { 92 continue; 93 } 94 else if(str[i]!=‘ ‘ && mark==0) { 95 mark = 1; 96 result += str[i]; 97 } 98 else if(str[i]!=‘ ‘ && mark==1) { 99 mark = 1; 100 result += str[i]; 101 } 102 else if(str[i]==‘ ‘ && mark==1) { 103 break; 104 } 105 } 106 return result; 107 } 108 };
时间: 2024-10-05 02:50:39