7.Reverse Integer
Given a 32-bit signed integer, reverse digits of an integer.
Example 1:
Input: -123 Output: -321
Example 2:
Input: 120 Output: 21
Note:
Assume we are dealing with an environment which could only hold integers within the 32-bit signed integer range. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.
菜鸡的思路:如果知道这个数的长度,就可以轻松地通过对10取模的方法,得到每位上面的数字,再乘以对应的个十百千万,加起来就好了。只不过要注意得到的ans的大小不要超过32-bit。
写完之后看了看大佬们的做法,大佬们的代码精炼无比,自己也学着改得简短了一些。主要思路是,求数字的长度和完成reverse这个过程其实是可以合并的。
另外,对符号的判断,用c++的话其实不是必要的,比如说-17%10=-7;所以说如果原数是负数的话,经过上面的计算累加,仍然是负数,当然,其他语言对负数取模是不是这样算的我就不清楚了。