Giter Site home page Giter Site logo

Comments (3)

xiongcaihu avatar xiongcaihu commented on May 5, 2024 5

思路
转换成数字,再进行比较
由于版本号是这样的格式 a.b.c.d,且a,b,c,d的范围都是0-9,偶尔会有前导0的组合,比如001,002,所以可以用一个四位数表示,去除前导0用parseInt即可。

/**
 * @param {string} version1
 * @param {string} version2
 * @return {number}
 */
var compareVersion = function (version1, version2) {
    var a = 0,
        b = 0;
    version1.split(".").forEach((item, index) => {
        a += parseInt(item) * 10 ** (3 - index)
    });

    version2.split(".").forEach((item, index) => {
        b += parseInt(item) * 10 ** (3 - index)
    });

    return a > b ? 1 : a == b ? 0 : -1;
};

image

from leetcode.

yjua avatar yjua commented on May 5, 2024 1

转换成数字大小进行比较

function compareVersion(v1,v2){
    v1 = v1.split('.');
    v2 = v2.split('.');
    let len = v1.length > v2.length ? v1.length : v2.length;
    let num1 = 0,num2 = 0;
    for(let i = 0; i < len; i++){
        if(v1[i] !== undefined){
            num1 += parseInt(v1[i]) * Math.pow(10,len-1-i);
        }
        if(v2[i] !== undefined){
            num2 += parseInt(v2[i]) * Math.pow(10,len-1-i);
        }
    }
    let result = num1 - num2;
    return result > 0 ? 1 : (result == 0 ? 0 : -1);
}

from leetcode.

lvguofeng1303 avatar lvguofeng1303 commented on May 5, 2024

认领

from leetcode.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.