zoukankan      html  css  js  c++  java
  • leetcode:String to Integer (atoi)

    问题

    输入:一个表示数字的字符串,须要考虑不同的输入形式。

    输出:相应的整数

    特殊输入形式:
    1.输入開始几个字符为空格
    2.考虑正负号
    3.数字字符不属于[0,9]时。输出当前结果
    4.字符串代表的数字大于INT_MAX或者小于INT_MIN时输出INT_MAX或者INT_MIN。


    class Solution {
    
    // out of range, to avoid this we use long long
    public:
    	int atoi(const char *str) {
    		
    		if(str == NULL) return 0;
    		while (*str == ' ')
    			str++;
    		int sign = 1;
    		if(*str == '-')
    		{
    			sign = -1;
    			str++;
    		}
    		else if(*str == '+')
    			str++;
    		long long ans = 0;
    		while (*str >= '0' && *str <= '9')
    		{
    			ans = ans*10+*str-'0';
    			if(ans > INT_MAX)//out of range
    				return sign < 0 ? INT_MIN : INT_MAX;
    			str++;
    		}
    		ans *= sign;
    		return (int)ans;
    	}
    };

    附录:
    long long的使用说明
    在做ACM题时,经常都会遇到一些比較大的整数。而经常使用的内置整数类型经常显得太小了:当中long 和 int 范围是[-2^31,2^31-1],即-2147483648~2147483647。

    而unsigned范围是[0,2^32-1],即0~4294967295。也就是说。常规的32位整数仅仅可以处理40亿下面的数。


      那遇到比40亿要大的数怎么办呢?这时就要用到C++的64位扩展了。不同的编译器对64位整数的扩展有所不同。

    基于ACM的须要,以下仅介绍VC6.0与g++编译器的扩展。
      VCVC6.0的64位整数分别叫做__int64与unsigned __int64,其范围各自是[-2^63, 2^63-1]与[0,2^64-1],即-9223372036854775808~9223372036854775807与0~18446744073709551615(约1800亿亿)。

    对64位整数的运算与32位整数基本同样。都支持四则运算与位运算等。当进行64位与32位的混合运算时,32位整数会被隐式转换成64位整数。可是,VC的输入输出与__int64的兼容就不是非常好了。假设你写下这样一段代码:


    1   __int64 a;
    2  cin >> a;
    3  cout << a;


    那么,在第2行会收到“error C2679: binary '>>' : no operator defined which takes a right-hand operand of type '__int64' (or there is no acceptable conversion)”的错误;在第3行会收到“error C2593: 'operator <<' is ambiguous”的错误。那是不是就不能进行输入输出呢?当然不是,你能够使用C的写法:
    scanf("%I64d",&a);
    printf("%I64d",a);
    就能够正确输入输出了。当使用unsigned __int64时。把"I64d"改为"I64u"就能够了。
      OJ通常使用g++编译器。其64位扩展方式与VC有所不同,它们分别叫做long long 与 unsigned long long。

    处理规模与除输入输出外的用法同上。对于输入输出,它的扩展比VC好。既能够使用
    1long long a;
    2cin>>a;
    3cout<<a;
    也能够使用
    scanf("%lld",&a);
    printf("%lld",a);
    */

  • 相关阅读:
    PAT (Advanced Level) 1060. Are They Equal (25)
    PAT (Advanced Level) 1059. Prime Factors (25)
    PAT (Advanced Level) 1058. A+B in Hogwarts (20)
    PAT (Advanced Level) 1057. Stack (30)
    PAT (Advanced Level) 1056. Mice and Rice (25)
    PAT (Advanced Level) 1055. The World's Richest (25)
    PAT (Advanced Level) 1054. The Dominant Color (20)
    PAT (Advanced Level) 1053. Path of Equal Weight (30)
    PAT (Advanced Level) 1052. Linked List Sorting (25)
    PAT (Advanced Level) 1051. Pop Sequence (25)
  • 原文地址:https://www.cnblogs.com/llguanli/p/6940432.html
Copyright © 2011-2022 走看看