标签:integer int += str index public while ret tco
class Solution { public: int myAtoi(string str) { int index = -1; int result = 0; int base = 10; int ssize = str.size(); bool negtive = false; while (++index < ssize && (str[index] == ‘ ‘)); if (index < ssize){ if (str[index] == ‘+‘) { ++index; } else if (str[index] == ‘-‘) { negtive = true; ++index; } } if (index < ssize && str[index] == ‘0‘){ ++index; if (index < ssize && (str[index] == ‘X‘ || str[index] == ‘x‘)){ base = 16; ++index; } } while (index < ssize){ char c = str[index]; int v = 0; if (base == 10){ if (c >= ‘0‘ && c <= ‘9‘){ v = c - ‘0‘; } else { break; } } else if (base == 16){ if (c >= ‘0‘ && c <= ‘9‘){ v = c - ‘0‘; } else if (c >= ‘a‘ && c <= ‘f‘){ v = 10 + c - ‘a‘; } else if (c >= ‘A‘ && c <= ‘F‘){ v = 10 + c - ‘A‘; } else { break; } } if (negtive){ if ((INT_MIN + v)/base > (result)){ result = INT_MIN; break; } else { result *= base; result -= v; } } else { if ((INT_MAX - v)/base < (result)){ result = INT_MAX; break; } else { result *= base; result += v; } } index ++; } return result; } };
leetcode problem 8: String to Integer (atoi)
标签:integer int += str index public while ret tco
原文地址:http://www.cnblogs.com/nosaferyao/p/7857940.html