leetcode.com-problemset-all-007 - Reverse Integer

- 4 mins

题目描述

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

难易程度

Example:

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实现

方法一

<?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;
        
    }
}

Go实现

方法一

// 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
}

PS

rss facebook twitter github gitlab youtube mail spotify lastfm instagram linkedin google google-plus pinterest medium vimeo stackoverflow reddit quora quora