Table of Contents
Problem Statement
The array-form of an integer num
is an array representing its digits in left to right order.
- For example, for
num = 1321
, the array form is[1,3,2,1]
.
Given num
, the array-form of an integer, and an integer k
, return the array-form of the integer num + k
.
Example 1:
Input: num = [1,2,0,0], k = 34
Output: [1,2,3,4]
Explanation: 1200 + 34 = 1234
LOGIC
We have 2 numbers lets say number_1 and number_2.
- Add last digit of above 2 numbers until first number is greater than 0.
- Save the output in result array by incrementing index by 1.
- Take care of carry handling.
- Repeat the same operation for number_2.
- At the end reverse the result array using Collections.reverse().
JAVA CODE Add to Array-Form of Integer
class Solution {
public List<Integer> addToArrayForm(int[] num, int k) {
List<Integer> result = new ArrayList<Integer>();
int digit = 0, carry = 0, j = 0;
for(int i = num.length-1; i>=0; i--){
digit = num[i] + carry + (k%10);
if (digit > 9) {
carry = 1;
} else {
carry = 0;
}
digit = digit % 10;
result.add(j++, digit);
if (k > 0) {
k = k / 10;
}
}
while (k > 0) {
digit = carry + (k%10);
if (digit > 9) {
carry = 1;
} else {
carry = 0;
}
digit = digit % 10;
result.add(j++, digit);
if (k > 0) {
k = k / 10;
}
}
if (carry > 0) {
result.add(j++, carry);
}
Collections.reverse(result);
return result;
}
}
Golang solution
func addToArrayForm(num []int, k int) []int {
result := []int{}
carry := 0
for i := len(num) - 1; i >= 0; i-- {
if k > 0 {
lastDigit := k % 10
newDigit := lastDigit + carry + num[i]
carry = 0
if newDigit > 9 {
carry = 1
newDigit = newDigit % 10
}
result = append(result, newDigit)
k = k / 10
} else {
newDigit := carry + num[i]
carry = 0
if newDigit > 9 {
carry = 1
newDigit = newDigit % 10
}
result = append(result, newDigit)
}
}
for k > 0 {
lastDigit := k % 10
newDigit := lastDigit + carry
carry = 0
if newDigit > 9 {
carry = 1
newDigit = newDigit % 10
}
result = append(result, newDigit)
k = k / 10
}
if carry == 1 {
result = append(result, carry)
}
i := 0
j := len(result) - 1
for i < j {
result[i], result[j] = result[j], result[i]
i++
j--
}
return result
}
Visit https://codeandalgo.com/interview-questions/ for more problems
Leave a Reply