【LEETCODE】#7 反转整数

xiaoxiao2021-02-28  34

Given a 32-bit signed integer, reverse digits of an integer.

Example 1:

Input: 123 Output: 321

Example 2:

Input: -123 Output: -321

Example 3:

Input: 120 Output: 21

Note: Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−231,  231 − 1]. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.


C++:

不需要把x分成大于0和小于0

-2^31如果转成正数会出错

返回y,会强制类型转换

class Solution { public: int reverse(int x) { long long int y=0; while(x){ y*=10; y+=x; x/=10; } if(y>pow(2,31)-1 || y<-pow(2,31)){ return 0; } else{ return y; } } };

C:

int reverse(int x) { int t; long y=0; for(t=x;t;t/=10){ y=y*10+t; if(y>pow(2,31)-1||y<-pow(2,31))return 0;    //OVERFLOW } return (int)y; }

 

转载请注明原文地址: https://www.6miu.com/read-2633089.html

最新回复(0)