美文网首页
java/c#/js超大整数比较思路

java/c#/js超大整数比较思路

作者: 吉凶以情迁 | 来源:发表于2023-02-20 15:08 被阅读0次

    由于我的app不再用版本号比较版本,而是用编译时间,因此我就想到了超大整数函数解决这个问题

    public class Main {
        public static void main(String[] args) {
            BigInteger num1 = new BigInteger("202302031422");
            BigInteger num2 = new BigInteger("202302031433");
    
            int result = num1.compareTo(num2);
    
            if (result < 0) {
                System.out.println(num1 + " 小于 " + num2);
            } else if (result > 0) {
                System.out.println(num1 + " 大于 " + num2);
            } else {
                System.out.println(num1 + " 等于 " + num2);
            }
        }
    }
    
    

    思路2

    String num1 = "202302031422";
    String num2 = "202302031433";
    
    // 比较长度,长度不同的先返回
    int len1 = num1.length();
    int len2 = num2.length();
    if (len1 < len2) {
        System.out.println(num1 + " 小于 " + num2);
    } else if (len1 > len2) {
        System.out.println(num1 + " 大于 " + num2);
    } else {
        // 长度相同,逐位比较
        for (int i = 0; i < len1; i++) {
            char c1 = num1.charAt(i);
            char c2 = num2.charAt(i);
            if (c1 < c2) {
                System.out.println(num1 + " 小于 " + num2);
                return;
            } else if (c1 > c2) {
                System.out.println(num1 + " 大于 " + num2);
                return;
            }
        }
        System.out.println(num1 + " 等于 " + num2);
    }
    

    js

    et num1 = "202302031422";
    let num2 = "202302031433";
    
    let result = BigInt(num1) < BigInt(num2) ? num1 + " 小于 " + num2
                    : BigInt(num1) > BigInt(num2) ? num1 + " 大于 " + num2 
                    : num1 + " 等于 " + num2;
    
    console.log(result);
    

    c#

    using System;
    using System.Numerics;
    
    class Program
    {
        static void Main(string[] args)
        {
            string num1 = "202302031422";
            string num2 = "202302031433";
    
            BigInteger bigInt1 = BigInteger.Parse(num1);
            BigInteger bigInt2 = BigInteger.Parse(num2);
    
            int result = bigInt1.CompareTo(bigInt2);
    
            if (result < 0)
            {
                Console.WriteLine(num1 + " 小于 " + num2);
            }
            else if (result > 0)
            {
                Console.WriteLine(num1 + " 大于 " + num2);
            }
            else
            {
                Console.WriteLine(num1 + " 等于 " + num2);
            }
        }
    }
    

    相关文章

      网友评论

          本文标题:java/c#/js超大整数比较思路

          本文链接:https://www.haomeiwen.com/subject/tergkdtx.html