Skip to content

Instantly share code, notes, and snippets.

@rohanjai777
Created August 27, 2023 07:51
Show Gist options
  • Save rohanjai777/8435817aeafd9a7f9559653911fc8770 to your computer and use it in GitHub Desktop.
Save rohanjai777/8435817aeafd9a7f9559653911fc8770 to your computer and use it in GitHub Desktop.
public class Solution {
public int[] plusOne(int[] A) {
ArrayList<Integer> al = new ArrayList<>();
//add 1 to last of element
int sum = (A[A.length-1]+1)%10;
int carry = (A[A.length-1]+1)/10;
al.add(sum);
//loop from second last to first
for(int i=A.length-2;i>=0;i--){
int num = A[i]+carry;
sum = num%10;
carry = num/10;
al.add(sum);
}
if(carry != 0){ //it has no starting zeros
al.add(carry);
} else { //removing zeros
while(al.get(al.size()-1) == 0 ){
al.remove(al.size()-1);
}
}
//generate response
int res[] = new int[al.size()];
for(int i=0;i<res.length;i++){
res[i] = al.get(res.length-i-1);
}
return res;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment