Skip to content

Latest commit

 

History

History
50 lines (36 loc) · 1.47 KB

165.md

File metadata and controls

50 lines (36 loc) · 1.47 KB

✏️Leetcode基础刷题之(Leetcode基础刷题之PHP解析(165. Compare Version Numbers)

2019-09-20 吴亲库里 库里的深夜食堂


✏️描述

给比较两个版本号,如果版本1大于版本二,返回1,小于返回-1,否则返回0。


✏️题目实例

✏️题目分析

主要需要注意一些非常规的情况,常规的就是分割字符串,然后一位位比较,非常规 的比如01.1类似这种的,所以最终需要考虑非常规情况。

    /**
     * @param String $version1
     * @param String $version2
     * @return Integer
     */
    function compareVersion($version1, $version2) {
      
        $v1=explode('.',$version1);
        $v2=explode('.',$version2);
    
            $max=max(count($v1),count($v2));
          for($i=0;$i<$max;$i++){
           $res1=$i<count($v1)?intval($v1[$i]):0;
           $res2=$i<count($v2)?intval($v2[$i]):0;
           if($res1<$res2) return -1;
           else if($res1>$res2) return 1;
          }
        
        return 0;  
    }

联系