LeetCode 7.Reverse Integer
Description:
Reverse digits of an integer.
Example1: x = 123, return 321
Example2: x = -123, return -321
分析:
主要考虑两方面:输入数字是以0结尾(无论多少个0);溢出怎么处理。
好在题目也给了一些提示,溢出返回0即可
利用C++11新增的函数string to_string(int), long long int stoll(string), 以及STL中的reverse函数可以解决该题。
- string to_string(int) : 将int类型转化为string类型
- long long int stoll(string): 将string类型转化为long long int类型
- reverse函数逆序转换
代码如下:
1 | class Solution { |
Another Solution:参考Discussion中的一个解法,这是比较常规的解法
1 | class Solution { |
Similar Questions:
LeetCode 8.String to Integer(atoi)
Implement atoi to convert a string to an integer.
Requirements for atoi:
The function first discards as many whitespace characters as necessary until the first non-whitespace character is found. Then, starting from this character, takes an optional initial plus or minus sign followed by as many numerical digits as possible, and interprets them as a numerical value.
The string can contain additional characters after those that form the integral number, which are ignored and have no effect on the behavior of this function.
If the first sequence of non-whitespace characters in str is not a valid integral number, or if no such sequence exists because either str is empty or it contains only whitespace characters, no conversion is performed.
If no valid conversion could be performed, a zero value is returned. If the correct value is out of the range of representable values, INT_MAX (2147483647) or INT_MIN (-2147483648) is returned.
Difficulty:Medium
分析:
这道题没看atoi的一些要求的话算是比较难的,因为不清楚atoi怎么处理输入的string。
参考atoi的要求,可得出下面4点:
- 去掉首部多余的空格
- 去掉尾部多余的不合法字符
- 符号位的处理
溢出的处理
可利用循环将首部空格去掉;标记符号位,以方便后面符号输出处理;因为输入的字符串只能是这样一种形式空格-符号位-数字-其他字符,因此再利用一个循环可把数字提取出来,舍弃掉尾部的非法字符。
代码如下:
1 | class Solution { |