Tutorialspoint
Problem
Solution
Submissions

Plus One

Certification: Basic Level Accuracy: 0% Submissions: 0 Points: 5

Write a C program to increment a large integer represented as an array of digits by one. Given a non-empty array of decimal digits representing a non-negative integer, increment the integer by one and return the resulting array of digits. The most significant digit is at the first position of the array.

Example 1
  • Input: digits = [1, 2, 3]
  • Output: [1, 2, 4]
  • Explanation: The array [1, 2, 3] represents the integer 123. Adding 1 gives 124, which is represented as [1, 2, 4].
Example 2
  • Input: digits = [9, 9, 9]
  • Output: [1, 0, 0, 0]
  • Explanation: The array [9, 9, 9] represents the integer 999. Adding 1 gives 1000, which is represented as [1, 0, 0, 0].
Constraints
  • 1 ≤ digits.length ≤ 100
  • 0 ≤ digits[i] ≤ 9
  • digits does not contain any leading zeros, except the number 0 itself
  • Time Complexity: O(n)
  • Space Complexity: O(n)
ArraysNumberMicrosoftPwC
Editorial

Login to view the detailed solution and explanation for this problem.

My Submissions
All Solutions
Lang Status Date Code
You do not have any submissions for this problem.
User Lang Status Date Code
No submissions found.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

Solution Hints

  • Start from the least significant digit (rightmost)
  • Add 1 to the digit and check if it becomes 10
  • If it becomes 10, set it to 0 and carry 1 to the next digit
  • Continue this process until there is no carry or no more digits
  • If there is still a carry after processing all digits, add a new digit 1 at the beginning of the array

Steps to solve by this approach:

 Step 1: Allocate memory for the result array with an extra slot for a potential carry.

 Step 2: Initialize a carry variable to 1 (this represents the "plus one" operation).
 Step 3: Iterate through the digits from right to left (least to most significant).
 Step 4: For each digit, add the current carry to it.
 Step 5: Calculate the new carry (digit + carry) / 10 and the new digit (digit + carry) % 10.
 Step 6: After processing all digits, check if there's still a carry.
 Step 7: If yes, include the carry at the beginning of the result array; if not, adjust the array size accordingly.

Submitted Code :