Search code examples
c++stringalgorithmcomparison

Compare two string as numeric value


How should I compare two string representing numbers in C++? I thought of converting to number of long long type but the problem is the numerical value represented by string can exceed the long long MAX limit. It is guaranteed that the string represents a numerical value.

There is a similar question in Java compare two numeric String values. but that makes use of the BigInteger Library that we don't have in C++.


Solution

  • Compare them digit by digit:

    a = "3254353245423345432423133423421"
    b = "3254353245423345432443133423421"
    
    for(int i = 0; i < a.length(); ++i):
        if ((a[i] - '0') < (b[i] - '0'))
        { 
            std::cout << "b is larger!" 
        }
    

    I'm sure you can take it from here if you want to find out whether b is larger than a, or if they are equal. Alternatively, if they are different lengths, the larger one wins! (Check for zeros at the beginning, i.e. "000443342") Don't forget to consider negative numbers.