如何确定逆序存储数字的数组相加结果的数组长度?
Hey there! Let's work through this reversed array addition problem—specifically that tricky part of figuring out how big the result array needs to be. Your current code has a couple of gaps we'll fix step by step.
Core Issues with Your Current Code
Right now, two key problems are holding you back:
- You’re setting the result array
zto the length ofx, butxandymight have different lengths (like your example where one is 3 digits and the other is 4). This will cause an array out-of-bounds error when the loop tries to access indices that don’t exist in the shorter array. - You aren’t accounting for a final carryover (like when adding 999 + 1, which results in 1000—you need an extra digit for that final 1).
How to Determine the Correct Result Array Size
The maximum possible length of your result array is the length of the longer input array + 1. Here’s why:
- If one input is longer than the other, the result needs to accommodate all the digits from the longer number, plus a potential carryover.
- Even if both arrays are the same length, adding their highest digits could produce a carryover that needs an extra slot (e.g., 999 + 999 = 1998, which is one digit longer than either input).
So first, calculate the length of the longer array, then add 1 to that value to reserve space for the final carryover.
Fixed Code Implementation
public static int[] add(int[] x, int[] y) { int maxLength = Math.max(x.length, y.length); // Initialize result array with extra space for potential final carry int[] z = new int[maxLength + 1]; int carry = 0; // Renamed from 'j' for clearer readability for (int i = 0; i < maxLength; i++) { // Use 0 for digits beyond the current array's length int digitX = (i < x.length) ? x[i] : 0; int digitY = (i < y.length) ? y[i] : 0; int sum = digitX + digitY + carry; z[i] = sum % 10; carry = sum / 10; } // Handle any remaining carry after processing all digits if (carry != 0) { z[maxLength] = carry; return z; } else { // Trim the extra unused slot if there's no final carry int[] trimmedResult = new int[maxLength]; System.arraycopy(z, 0, trimmedResult, 0, maxLength); return trimmedResult; } }
Breakdown of the Fixed Code
- Array Length Handling: We use
Math.max()to get the length of the longer input array, then create a result array that’s one slot bigger to cover carryover cases. - Out-of-Bounds Protection: For each iteration, we check if the current index exists in
xory—if not, we treat that digit as 0 (since numbers don’t have leading zeros, which translates to trailing zeros in our reversed arrays). - Final Carryover: After the loop, if there’s still a carry value left, we add it to the last slot of the result array. If not, we trim the array to remove the unused final slot (this is optional but keeps the result clean).
Test It With Your Examples
Let’s test your sample inputs:
x = {9,3,8}(839) andy = {9,3,0,2}(2039):
The loop processes all 4 digits of the longer array, no final carry, so we return{8,7,8,2}—which translates to 2878, the correct sum of 839 + 2039.- Another test case:
x = {9,9,9}(999) andy = {1}(1):
After processing all 3 digits, we have a carry of 1 left, so the result array becomes{0,0,0,1}—which is 1000, the correct sum.
内容的提问来源于stack exchange,提问作者Fluxia
相关产品推荐
相关产品推荐

