Created
February 21, 2014 12:30
-
-
Save kingsamchen/9133445 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
int StrToDecInt(const char* str) | |
{ | |
static const int kMAX = (int)((unsigned)~0 >> 1); | |
static const int kMIN = -(int)((unsigned)~0 >> 1) - 1; | |
static const int kMAX_DIV = (int)((unsigned)~0 >> 1) / 10; | |
static const int kMIN_DIV = (int)((((unsigned)~0 >> 1) + 1) / 10); | |
static const int kMAX_R = (int)((unsigned)~0 >> 1) % 10; | |
static const int kMIN_R = (int)((((unsigned)~0 >> 1) + 1) % 10); | |
int n = 0; | |
int sign = 1; | |
int c; | |
while (isspace(*str)) | |
++str; | |
if (*str == '+' || *str == '-') { | |
if (*str == '-') | |
sign = -1; | |
++str; | |
} | |
while (isdigit(*str)) { | |
c = *str - '0'; | |
if (sign > 0 && (n > kMAX_DIV || (n == kMAX_DIV && c >= kMAX_R))) { | |
n = kMAX; | |
break; | |
} else if (sign < 0 && (n > kMIN_DIV || (n == kMIN_DIV && c >= kMIN_R))) { | |
n = kMIN; | |
break; | |
} | |
n = n * 10 + c; | |
++str; | |
} | |
return sign > 0 ? n : -n; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment