LeedCode OJ -- String to Integer (atoi)

点击打开题目链接

题目意思就是自己实现一个atoi函数,也就是将字符串转换成int型。

关于INT_MAX和INT_MIN, 只是在<limits.h>文件中定义的宏..分别是int型可以表示的最大值和最小值

还有就是定义大整数常量的时候,会出现这种警告:warning: this decimal constant is unsigned only in ISO C90

c的标准写道:

The C90 rule that the default type of a decimal integer constant is either int, long, or
unsigned long, depending on which type is large enough to hold the value without overflow,
simplifies the use of constants. The choices in C99 are int, long and long long.
C89 added the suffixes U and u to specify unsigned numbers. C99 adds LL to specify long
long.
Unlike decimal constants, octal and hexadecimal constants too large to be ints are typed as
unsigned int if within range of that type, since it is more likely that they represent bit
patterns or masks, which are generally best treated as unsigned, rather than “real” numbers.
Little support was expressed for the old practice of permitting the digits 8 and 9 in an octal
constant, so it was dropped in C89.
A proposal to add binary constants was rejected due to lack of precedent and insufficient utility.
Despite a concern that a “lower-case-l” could be taken for the numeral one at the end of a
numeric literal, the C89 Committee rejected proposals to remove this usage, primarily on the
grounds of sanctioning existing practice.

解决方式:

1 在常数后面增加一个UL标识,或者ULL表示,如4294967295UL,这样就不会报警了
2 使用十六进制的数字,如0xFFFFFFFF
3 使用gcc -std=c99 用99标准来编译

附上代码:

 

 1 class Solution {

 2 public:

 3         int atoi(const char *str) {

 4                 unsigned long long ans = 0;

 5                 // is positive ?

 6                 int flag = 1;

 7                 while (*str == ' ') str++;

 8                 if (*str == '+') {

 9                         str++;

10                 } else if (*str == '-') {

11                         flag = 0;

12                         str++;

13                 }

14                 while (*str != '\0') {

15                         if ((*str) < '0' || (*str) > '9')

16                                 break;

17                         ans = ans * 10 + (*str) - '0';

18                         if (flag and ans > 2147483647ULL) {

19                                 return INT_MAX;

20                         } else if (!flag and ans > 2147483648ULL) {

21                                 return INT_MIN;

22                         }

23                         str++;

24                 }

25 

26                 if (!flag) {

27                         ans = -ans;

28                 }

29                 return (int)ans;

30         }

31 };

 


 

 

你可能感兴趣的:(Integer)