7 Reverse Integer


  1. int reverse(int x) {
  2.     long long ans=0;
  3.     const int maxint=0x7fffffff;
  4.     const int minint=0x80000000;
  5.     do(x!=0){
  6.         ans=ans*10+(x%10);//对正数负数都能处理
  7.         x/=10;
  8.     }while(x!=0);
  9.     if(ans<minint || ans>maxint){
  10.         ans=0;
  11.     }
  12.     return ans;
  13. }


008

  1. int myAtoi(char* str) {
  2.     int i=0,sign=0;
  3.     long long n=0;//非常重要,一定要定义long long
  4.     const int maxint=0x7FFFFFFF;
  5.     const int minint=0x80000000;
  6.     const long long max=0x100000000;//非常重要,绝对值要大于minint的绝对值
  7.     while(str[i]==' ' || str[i]=='\n' || str[i]=='\t')
  8.         i++;
  9.     if(str[i]=='+'){
  10.         i++;
  11.     }
  12.     else{
  13.         if(str[i]=='-'){
  14.             sign=1;
  15.             i++;
  16.         }
  17.     }
  18.     
  19.     for(;str[i]!='\0';i++){
  20.         if(str[i]<='9' && str[i]>='0'){
  21.             n=n*10+(str[i]-'0');
  22.             if(n>max)n=max;//非常重要
  23.         }else{
  24.             break;
  25.         }
  26.     }
  27.     if(sign)n=-n;
  28.     if(n>maxint)n=maxint;
  29.     if(n<minint)n=minint;
  30.     return n;
  31. }
  32. /*
  33. "9223372036854775809"
  34. "2147483648" 
  35. "-2147483648"
  36. " -11919730356x"
  37. */



















12-08 12:45