CC-7 : Given an integer represented as elements of array, add 1 to the integer.
Description:
Given an input integer array arr, where each index of arr represents a digit of an integer. We need to add 1 to the integer using array operations.
Test cases and expected outputs:
| Input Parameters | Expected outputs |
|---|---|
| Integer 70 as array arr={7,0} | 0,7,1 |
| Integer 799 as array arr={7,9,9} | 0,8,0,0 |
| Integer 000 as array arr={0,0,0} | 0,0,0,1 |
| Integer 9999 as array arr={9,9,9,9} | 1,0,0,0,0 |
| Integer 12345 as array arr={1,2,3,4,5} | 0,1,2,3,4,6 |
Note: 0 is added at 0th index in outputs in all rows. This is to handle cases where adding 1 may result in new index being required. Refer test case 4 above.
Pseudocode:
| The java method should accept following input parameters: arr (int array). The arrays elements are the digits of the input integer to which 1 needs to be added. |
| Create a new array of integers addedArr with length one greater than input array arr. This new array will be used to store the arr integers elements after 1 is added to it. |
| Initialize a boolean variable addOneToNextIndex, which we will use as a flag to indicate that the sum of two integer digits is greater than 9, so 1 needs to be carried over to next index. |
| Iterate arr backwards starting from (arr.length-1) to 0 with idx as loop variable:
If idx=arr.length-1:
Add 1 to arr[idx].
If sum from above step < 10, add the sum to addedArr[idx+1].
If sum from above addition>=10, add 0 to addedArr[idx+1] and add 1 to arr[idx] in next iteration using addOneToNextIndex.
|
| After for loop is complete, return addedArr, it contains the integer with 1 added to input integer. |
Code:
public int[] arrayPlusOneToIntegerUsingArray(int[] arr) throws Exception{
int[] addedArr=new int[arr.length+1];
boolean addOneToNextIndex=false;
for (int idx=arr.length-1; idx>=0; idx--) {
if ((addOneToNextIndex==true)||(idx==arr.length-1)) {
if (arr[idx]+1<10) {
addedArr[idx+1]=arr[idx]+1;
addOneToNextIndex=false;
}else {
addedArr[idx]=0;
addOneToNextIndex=true;
}
if ((idx==0)&&(addOneToNextIndex==true)) {
addedArr[0]=1;
}
}else {
addedArr[idx+1]=arr[idx];
}
}
return addedArr;
}
Click here to download and run code and test cases !
| About Us | Privacy Policy | Contact us |