Problem
Given a signed 32-bit integer x, return x with its digits reversed. If reversing x causes the value to go outside the signed 32-bit integer range [-231, 231 – 1], then return 0.
Assume the environment does not allow you to store 64-bit integers (signed or unsigned).
Example 1:
Input: x = 123
Output: 321
Example 2:
Input: x = -123
Output: -321
Example 3:
Input: x = 120
Output: 21
Example 4:
Input: x = 0
Output: 0
Constraints:
- -231 <= x <= 231 – 1
Solution
function reverse(x: number): number {
if(x==0) return 0;
if(x<0){
x=-x;//去负号
return -calculate(x);
}
if(x>0){
return calculate(x);
}
};
function calculate(x:number):number{
var sum = 0;
var s =x.toString();
var l= s.length;
for(let i =l-1;i>-1;i--){
let c = s.charAt(i);//长度是l,最后一个字符的序号是l-1
let e = 10 ** i;//指数就是这个数在字符串里的序号
let n= +c;//+n将字符串转化为数字
sum += n * e;
}
if(sum>2**31-1 ||sum<-2**31) sum=0;
return sum;
}
心得
目前水平比较渣渣所以先做简单的题……
这题是让把一个整数反转过来,思路就是把一个数倒过来其实就是把这个数的位数从后往前对应。然后再看这一位数字对应的需要乘以多少个10即可。
来源:
力扣(LeetCode)
链接:https://leetcode-cn.com/problems/reverse-integer
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。