Leetcode基础刷题之PHP解析(7. Reverse Integer)

栏目: PHP · 发布时间: 6年前

2 0 1 9 -6-20   期四  

Leetcode基础刷题 PHP 解析(103. Binary Tree Zigzag Level Order Traversal)

Leetcode基础刷题之PHP解析(7. Reverse Integer)

给定一个32位整形,让我们反转它的整数,也就是说如果是负数,只是把负数后的数字进行反转,依然是负数。

这里唯一要注意的是note下说如果给定我们的环境只能存储32位带符号的整数范围,溢出的话,直接返回0.

/**
     * @param Integer $x
     * @return Integer
     */
    function reverse($x) {
        $true=1;
        if($x<0) $true= -1;
        $x *= $true;
        $x=strrev($x);
        $x = intval($x) * $true;
        if ($x >= pow(2, 31) - 1) return 0;
        if ($x <= pow(2, 31) * -1) return 0;
        return $x;
    }

看到一哥们的解,你们感受一下

/**
     * @param Integer $x
     * @return Integer
     */
    function reverse($x) {
 
          if($x == 0) return $x;
        $num = abs($x);
        $sign = $x<0 ? -1 : 1;
        $digits = array();
        while($num>0){
            array_push($digits, $num%10);
            $num = floor($num/10);
        }
        $reversedNum = 0;
        $factor = 1;
        for($i = count($digits)-1; $i>=0; --$i) {
            $reversedNum += $digits[$i]*$factor;
            $factor*= 10;
        }
        if(($sign>0 && $reversedNum > 2147483648-1) || ($sign<0 && $reversedNum >2147483648))
            return 0;
        return $sign*$reversedNum;
        
    }

Github整理地址 : https://github.com/wuqinqiang/leetcode-php


以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Algorithms to Live By

Algorithms to Live By

Brian Christian、Tom Griffiths / Henry Holt and Co. / 2016-4-19 / USD 30.00

A fascinating exploration of how insights from computer algorithms can be applied to our everyday lives, helping to solve common decision-making problems and illuminate the workings of the human mind ......一起来看看 《Algorithms to Live By》 这本书的介绍吧!

RGB转16进制工具
RGB转16进制工具

RGB HEX 互转工具

html转js在线工具
html转js在线工具

html转js在线工具

HEX HSV 转换工具
HEX HSV 转换工具

HEX HSV 互换工具