2 0 1 9 -6-20 星 期四 开 始 吧
上 一 题 链 接 Leetcode基础刷题 PHP 解析(103. Binary Tree Zigzag Level Order Traversal)
题 目 描 述
给定一个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
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网
猜你喜欢:- Apache Flink 零基础入门(一):基础概念解析
- Apache Flink 零基础入门(一):基础概念解析
- JStorm 源码解析:基础线程模型
- React Hooks 解析(上):基础
- TypeScript基础入门之模块解析(一)
- TypeScript基础入门之模块解析(二)
本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
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》 这本书的介绍吧!