1

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++.

Community
  • 1
  • 1
Prashant Bhanarkar
  • 930
  • 3
  • 14
  • 32

4 Answers4

11

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.

Jossie Calderon
  • 1,393
  • 12
  • 21
  • @PrashantBhanarkar Please read my last line. "Alternatively, if they are different lengths, the larger one wins!" – Jossie Calderon Jul 23 '16 at 16:51
  • @BlackMoses, Covered by the text of the answer. – chris Jul 23 '16 at 16:52
  • @BlackMoses Please read my last line, for god sakes...." (Check for zeros at the beginning, i.e. "000443342")" – Jossie Calderon Jul 23 '16 at 16:52
  • 1
    The main problem then is negative numbers. – chris Jul 23 '16 at 16:52
  • @chris That can also be checked for, but I'm not here to do homework. (Although I will add the idea to the answer) – Jossie Calderon Jul 23 '16 at 16:53
  • This is very interesting. My answer with the code and details gets downvoted, but the newer answer with my exact details and no code gets upvoted. – Jossie Calderon Jul 23 '16 at 16:55
  • `a[i] - 0` makes no sense. You probably meant `'0'`, also if guaranteed that they are both valid numbers, converting them to actual numbers isn't needed – adnan_e Jul 23 '16 at 16:58
  • Why `a[i] - 0`? Did you mean `a[i] - '0'`? And if the strings are the same length, and both are positive, `strcmp(a, b) < 0` would work. – evan Jul 23 '16 at 17:01
  • This would fail for the testcase compare("13325","13235") assuming compare is the function name for the above code snippet – Ayan May 15 '22 at 06:36
1

If you think about it a bit, its not hard. For simplicity we will assume two positive numbers with no leading zeros. If they have leading zeroes, discard them.

Now consider two numbers:
123456
23456
Its apparent that the first one is larger, because it is longer. This allows us to quickly solve most comparisons. Now, if they have equal length, just compare them from the beginning. The number with smaller leading digit is smaller. If they are equal, take the next digit.

Now what about other cases? Well, one positive and one negative number is easy, the negative one is smaller, period. If you have two negative numbers, then you have to do the same thing as you would when comparing two positive numbers, but this time the number with larger leading digit is smaller.


As was pointed to me in the comments, std::string already implements lexicographical comparison, which means that you only have to sanitize the strings into valid numbers, call std::string::compare and decide whether -1 means smaller (positive numbers) or larger (negative numbers).

Xarn
  • 3,460
  • 1
  • 21
  • 43
  • Note that the algorithm you describe in the last paragraph is exactly what comparing two strings does, so no need to reimplement it. – chris Jul 23 '16 at 16:54
  • @chris True, once you discard leading zeroes and assuming you have `std::string`s. The way the question is formulated reminds me of competitive coding problems and people in those for some reason tend to stick to C with C++ compiler (and thus char*). I also admit it didn't occur to me that its just a lexicographical comparison. – Xarn Jul 23 '16 at 16:58
1

If you are comparing two strings as integers,
chances are you are going to find yourself wanting to do other math as well.

Use GMP and save yourself the headaches.

#include <iostream>
#include <gmpxx.h>

int main(){

    mpz_class x("12323423434534234234234");
    mpz_class y("9994828945090011626439");

    std::cout << std::boolalpha;
    std::cout << (x < y) << '\n';
}

//example compilation:  g++ mycxxprog.cc -lgmpxx -lgmp

This may be overkill for your particular problem, as it increases the project dependencies.
Be sure to consider other options.

Trevor Hickey
  • 36,288
  • 32
  • 162
  • 271
0

Takes 2 strings as input, returns 1 if 2nd(b in this case) is larger, 0 otherwise.

int find(char a[],char b[])
{
    int i = 0;
    int flag = 0;
    if(a[0] == '-' && b[0] !='-')
    {
        printf("%s is larger: %s is -ve",b,a);
        return 1;
    }
    else if(b[0] == '-' && a[0] !='-')
    {
        printf("%s is larger: %s is -ve",a,b);
        return 0;
    }
    for(i = 0; i < strlen(a); ++i)
    {
        if(a[i] == '.' && b[i] != '.')
        {
            printf("%s is larger: %s is .",b,a);
            return 1;
        }
        else if(b[i] == '.' && a[i] != '.')
        {
            printf("%s is larger: %s is .",a,b);
            return 0;
        }
        else if(a[i] == '.' && b[i] == '.')
        {
            printf("passed\n");
            continue;
        }
        if ((a[i] - '0') < (b[i] - '0'))
        {
            flag =  1;
            //break;
        }
    }
    if(flag == 0)
        return 0;
    else
        return 1;
}
Ganesh Jadhav
  • 712
  • 6
  • 22