1189. Signed Number Compare

Easy1.5 points estimatedStringCustom Comparator

A spreadsheet engine must order cells that hold huge whole numbers stored as text. The strings a and b each hold a decimal integer with an optional leading '+' or '-' and any number of leading zeros, and each contains at least one digit. Both can be far too long for any built-in integer type.

Return -1 if a is smaller than b, 0 if they are equal, and 1 if a is larger. Treat "-0" and "+0" as the same value as "0". Do not convert the strings to numbers. Compare the signs first, then the digit counts after removing leading zeros, then the digits from left to right, and reverse the verdict when both numbers are negative.

Constraints: 1 <= a.length, b.length <= 1000. One pass over the strings runs in O(n) time with O(1) extra space.

Example 1

Input:
a = "-12", b = "7"
Output:
-1
Explanation:

A negative number is always smaller than a positive one, so the answer is -1.

Example 2

Input:
a = "+0042", b = "42"
Output:
0
Explanation:

After removing the sign and leading zeros both numbers are 42, so they are equal.

Example 3

Input:
a = "-9", b = "-10"
Output:
1
Explanation:

Both are negative; 10 has more digits than 9, so -10 is smaller and -9 is larger, giving 1.

Constraints

1 ≤ a.length, b.length ≤ 1000

each string has at least one digit

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.

Expected complexity

Time
O(n)
Space
O(1)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…