A Breaking Test case (or) a Problem Variant for Problem 6.2 v1.4.4

#1

For the problem 6.2 in v 1.4.4 Incrementing Big Integer, What if,
“The array of digits could also encode a negative decimal number”,
Then in that case, increment by one must move the number down in the opposite direction on the number line than on the wrong direction which would be indeed a decrement operation for negative number.

Assuming that a negative big decimal is a valid legal input, it would then break the posted solution.
Even if negative big decimal input is not expected or not a valid legal input the variant posed an interesting exercise to the brain.

Posting my solution to handle the negative numbers as well. (I took the freedom to alter the method signature a little bit to avoid code and input format clumsiness. To avoid input like [-5, 2] etc ). It is written in python.


def increment(L, sign):

i = len(L)-1 #start with the last element

while(i >=0 ):
    if sign == 'P':
        new_val = L[i]+1
        if new_val <= 9:
            L[i] = new_val
            break
        else:
            L[i] = 0
            i = i - 1
            continue
    elif sign == 'N':
        new_val = L[i] - 1
        if new_val < 0:
            L[i] = 9
            i = i - 1
            continue
        else:
            L[i] = new_val
            break

if L[0] == 0 and sign == 'P': #handle for MSB updated to 10 case.
    L = [1] + L
if L[0] == 9 and sign == 'N': #handle for [1, 'N'] case.
    L = [0]

return L

Valid inputs for sign are ‘P’ for positive and ‘N’ for negative decimals.
Examples:
a = [1,0,0]
increment(a, ‘N’) --> Should output [0, 9, 9]

a = [1,0,0]
increment(a, ‘P’) --> Should output [1, 0, 1]

0 Likes

#2

Hey Muthu,

Thanks for your reply, and you are right, the original description won’t work for input is negative number. We do modify that in the following version, 1.4.8 I think, and I am sorry that you don’t get the update.

About your python program, I think it is totally cool because it handles the case you mentioned beautifully, and it definitely looks like an interesting variant candidate. We definitely will take a look into this.

0 Likes

#3

Thanks Tsung-Hsien Lee. That was really kind of you :smiley:

0 Likes