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.
<?php
/**
* Created by PhpStorm.
* User: zhanglingyu
* Date: 2019-04-02
* Time: 14:59
*/
// 12ms
class Solution {
/**
* @param Integer $x
* @return Integer
*/
function reverse($x) {
$v = 1;
if ($x <= 0) {
$v = -1;
}
$x = $x * $v;
if ($x > 2147483647) {
return 0;
}
$res = '';
while ($x) {
$res .= $x%10;
$x = intval($x/10);
}
if ($res > 2147483647) {
return 0;
}
return $res * $v;
}
}
class Test extends \PHPUnit\Framework\TestCase
{
public function testReverse()
{
$solution = new Solution();
$int1 = 123;
$this->assertEquals($solution->reverse($int1), 321);
}
}
// 12ms
class Solution {
/**
* @param Integer $x
* @return Integer
*/
function reverse($x) {
$symbol = 1;
if ($x < 0) $symbol = -1;
$x *= $symbol;
$temp = strrev($x);
$temp = intval($temp) * $symbol;
if ($temp >= pow(2, 31) - 1) return 0;
if ($temp <= pow(2, 31) * -1) return 0;
return $temp;
}
}
// 4ms
func reverse(x int) int {
v := 1
if x < 0 {
v = -1
}
x = x * v
if x > 2147483647 {
return 0
}
var r int
for x > 0 {
r = r*10 + x%10
x = x/10
}
if r > 2147483647 {
return 0
}
return r * v
}
// 4MS
import "math"
func reverse(x int) (out int) {
for ; x != 0; x /= 10 {
out = out * 10 + x % 10
if out > math.MaxInt32 || out < -math.MaxInt32 - 1 {
return 0
}
}
return out
}
方法一
一般是自己实现的方法,其他方式
是在discuss
中查找的更为优秀的方法,用作学习和借鉴。