Given an integer array of variable length like so [9, 8, 8, 3] where each item in array could be 0 to 9, write a function that would take would interpret the array [9, 8, 8, 3] as a number 9883 and increment it by 1. The return of the function would be an integer array containing the addition like so [9,8,8,4]. No zeros in the first position like [0,1,2,3]. I initially suggested a possible solution of process to convert the integer array to String then convert to Integer or Long and then do the addition of 1 and then convert it back to integer array. That is not allowed because the solution should be able to handle a very large number. Practice Tip: Remove the initial text, if any, in the G docs for more viewing room for code.
public static int[] bigAdd(int[] digits) { int currentDigitsSum = 1; for (int i=digits.length - 1; i > -1; i--) { currentDigitsSum = digits[i] + currentDigitsSum; digits[i] = currentDigitsSum % 10; if (currentDigitsSum /10 ==0) { return digits; } else { currentDigitsSum /= 10; } } if (currentDigitsSum != 0) { int[] newDigits = new int[digits.length + 1]; System.arraycopy(digits, 0, newDigits, 1, digits.length); newDigits[0] = currentDigitsSum % 10; return newDigits; } return null; }
时间: 2024-11-13 09:17:47