Welcome!

By registering with us, you'll be able to discuss, share and private message with other members of our community.

SignUp Now!

leetcode problem no. 66 plus one

RISHI DUBEY

New member
Joined
Sep 27, 2024
Messages
3
class Solution {
public int[] plusOne(int[] digits) {
int sum=0;
for(int i=0;i<digits.length;i++)
{
sum=sum*10+digits;
}
sum=sum+1;
int h=sum;
int i=0;
while(sum>0) //count no. of digits
{
sum=sum/10;
i++;
}
digits=new int; // increase size of array as per required
for(int k=digits.length-1;k>=0;k--) //insert element in array
{
digits[k]=h%10;
h=h/10;
}
return digits;

}
}
Screenshot 2024-10-01 163845.png
 
Last edited:
There are a few issues in your code.
  1. Accessing array elements incorrectly:
    • In the line sum=sum*10+digits;, you're trying to add the entire array digits to sum. You should be adding individual elements from the digits array, i.e., digits.

    [*]Array resizing:
    • When you try to declare a new array with digits=new int;, you're missing the size in the array declaration. Java requires you to provide the size when creating an array (e.g., new int[size]).
    [*]Loss of the original digits array:
    • Instead of converting the entire array into a number and incrementing it (which can lead to overflow if the number is too large), it's better to handle the digits directly in the array to avoid these issues.

      first try yourself then look for the solution below.

    [*]Solution :
    Java:
    class Solution {    public int[] plusOne(int[] digits) {
            // Start from the last digit
            for (int i = digits.length - 1; i >= 0; i--) {
                // If the current digit is less than 9, we can just add 1 and return the result
                if (digits[i] < 9) {
                    digits[i]++;
                    return digits;
                }
                // If the current digit is 9, set it to 0 (since 9+1 = 10)
                digits[i] = 0;
            }
            
            // If we're here, that means all the digits were 9, so we need an extra digit
            // Create a new array with an extra space for the carry
            int[] result = new int[digits.length + 1];
            result[0] = 1; // Set the first digit to 1, rest are 0 by default
            return result;
        }
    }
 
Back
Top