165 - Compare Version Numbers

简单的思路:按照 . 进行分个,挨个比较大小

const compareVersion = function(version1, version2) {
  const version1Numbers = version1.split('.');
  const version2Numbers = version2.split('.');
  const len = Math.max(version2Numbers.length, version1Numbers.length)

  for (i = 0; i < len; ++i) {
      const number1 = Number(version1Numbers[i] ?? 0); // 将值转换为 number 进行比较
      const number2 = Number(version2Numbers[i] ?? 0);

      if ( number1 > number2 ) {
          return 1;
      }

      if ( number1 < number2 ) {
          return -1;
      }
  }

  return 0;
};

Subscribe to the newsletter

Get emails from me about web development, tech, and early access to new articles. I will only send emails when new content is posted. No spam.