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