Created
November 1, 2016 21:39
-
-
Save PetrGlad/e222397e0b9b793ff9f3d700fdff3cfd to your computer and use it in GitHub Desktop.
Array add - interview task
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.company; | |
import java.util.Arrays; | |
public class ArrayAdd { | |
public static int[] incArray(int[] digits, int base) { | |
assert base > 0; | |
final int[] result = new int[digits.length + 1]; | |
int carry = 1; // Increment value | |
for (int i = digits.length - 1; i >= 0; i--) { | |
assert digits[i] < base; | |
if ((digits[i] + carry) >= (base - 1)) { | |
result[i + 1] = 0; | |
carry = 1; | |
} else { | |
result[i + 1] = digits[i] + carry; | |
carry = 0; | |
} | |
} | |
if (carry > 0) | |
result[0] = carry; | |
return result; | |
} | |
public static int[] incArrayV2(final int[] digits, final int increment, final int base) { | |
assert base > 0; | |
final int[] result = new int[digits.length + 1]; | |
int carry = increment; | |
for (int i = digits.length - 1; i >= 0; i--) { | |
assert digits[i] >= 0; | |
final int d = digits[i] + carry; | |
result[i + 1] = Math.floorMod(d, base); | |
carry = d / base; | |
} | |
if (carry > 0) | |
result[0] = carry; | |
return result; | |
} | |
public static void main(String[] args) { | |
System.out.println(Arrays.toString(incArrayV2(new int[]{1, 3, 9}, 12, 10))); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment