I have started practicing problems in leetcode and I solved the following problem on LeetCode.
The challenge is :
Given a non-empty array of digits representing a non-negative integer, plus one to the integer.
The digits are stored such that the most significant digit is at the head of the list, and each element in the array contain a single digit.
You may assume the integer does not contain any leading zero, except the number 0 itself.
Example 1:
Input: [1,2,3]
Output: [1,2,4]
Explanation: The array represents the integer 123.
Example 2:
Input: [4,3,2,1]
Output: [4,3,2,2]
Explanation: The array represents the integer 4321.
I am trying to get better at writing good code for my solutions. Please give me your suggestions
class Solution {
public int[] plusOne(int[] a) {
int length = a.length-1;
while(length>=0)
{
a[length]=a[length]+1;
int carry = a[length]/10;
if(carry==1)
{
a[length]=0;
length=length-1;
}
else
break;
}
if(a[0]==0)
{
int [] array = new int[a.length+1];
array[0]=1;
for(int i=1;i<array.length-1;i++)
{
array[i]=0;
}
return array;
}
return a;
}
}