Skip to content

Welcome to Tech by Example

Menu
  • Home
  • Posts
  • System Design Questions
Menu

Plus one program or Add one to an integer array

Posted on February 1, 2022February 1, 2022 by admin

Overview

An integer array is given. Overall this integer array represents a number. So let’s say the integer array name is digits then digitis[i] denote the ith digit of the integer. The objective is to add 1 to that to that integer array. This has to be done without converting that array to a number of type int.

Example

Input: [1, 2]
Output: [1, 3]

Input: [9, 9]
Output: [1, 0, 0]

Program

Here is the program for the same.

package main

import "fmt"

func plusOne(digits []int) []int {

	lenDigits := len(digits)

	output := make([]int, 0)

	lastDigit := digits[lenDigits-1]

	add := lastDigit + 1
	carry := add / 10

	lastDigit = add % 10
	output = append(output, lastDigit)

	for i := lenDigits - 2; i >= 0; i-- {
		o := digits[i] + carry
		lastDigit = o % 10
		carry = o / 10
		output = append(output, lastDigit)
	}

	if carry == 1 {
		output = append(output, 1)
	}

	return reverse(output, len(output))
}

func reverse(input []int, length int) []int {
	start := 0
	end := length - 1

	for start < end {
		input[start], input[end] = input[end], input[start]
		start++
		end--
	}

	return input
}

func main() {
	output := plusOne([]int{1, 2})
	fmt.Println(output)

	output = plusOne([]int{9, 9})
	fmt.Println(output)
}

Output

[1 3]
[1 0 0]
©2025 Welcome to Tech by Example | Design: Newspaperly WordPress Theme