实现字符串到整形的转换

考虑:

1.考虑各种边界条件

2.考虑 正负数 

3.考虑整数 相加 溢出,注意 负数和整数的表示范围不同。负数最小数是  -(正数最大值+1)


int StrToInt(const char* str)
{
      int num = 0;
	  #define NULL 0
	  #define INT_MAX	 ((int)(~0U>>1))
      if(str == NULL)
      {
    	  return -1;
      }

            const char* digit = str;

            //scan ' ' char
            while(*digit==' '){
          	  digit++;
            }
            // the first char in the string maybe '+' or '-'
            int minus = 0;
            if(*digit == '+')
                  digit ++;
            else if(*digit == '-')
            {
                  digit ++;
                  minus = 1;
            }

            // the remaining chars in the string
            while(*digit != '\0')
            {
                  if((*digit >= '0')&&(*digit <= '9'))
                  {

                        num = num * 10 + (unsigned int)(*digit - '0');

                        // overflow
                        if(minus){
							if((unsigned int)num>INT_MAX+1){
								return 0;
							}
                        }else{
							if((unsigned int)num>INT_MAX){
								return 0;
							}
                        }
                        digit ++;
                  }
                  // if the char is not a digit, invalid input
                  else
                  {
                        num = 0;
                        break;
                  }
            }

            if(*digit == '\0')
            {
                  if(minus)
                        num = 0 - num;
            }

      return num;
}


你可能感兴趣的:(实现字符串到整形的转换)