Created
October 20, 2012 10:13
-
-
Save liyocee/3922871 to your computer and use it in GitHub Desktop.
Increments the least significant element of an array with any arbitrary integer
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
/* | |
* Write an algorithm that , given an array input (of integers), | |
increments the least significant element with any arbitrary integer. | |
f this element exceeds 9, carry accordingly to the next element, assign the remainder to the current element. | |
Proceed until the addition stops. Extend the array as necessary to accomodate special cases :) | |
Example: [1,2,9,9] + 1 = [1,3,0,0] | |
* */ | |
public class Problem1{ | |
public static void main(String[]args){ | |
Integer []arr={1,2,9,9}; | |
Integer incrementVal=1; | |
new Problem1().increment(arr,incrementVal); | |
} | |
public void increment(Integer []array,Integer val){ | |
String last; | |
int n=array.length-1; | |
int strlen; | |
array[n]=array[n]+val; /* increment the last value */ | |
for(;n>0;n--){ | |
if(array[n]>9){ | |
last=array[n].toString(); /* get the current value in string*/ | |
strlen=last.length(); | |
String toCarry=last.substring(0,strlen-1); /* get the value to be carried */ | |
String remainder=last.substring(strlen-1,strlen);/* get the remainder */ | |
array[n]=Integer.valueOf(remainder); /*assign the remainder to the current value */ | |
array[n-1]=array[n-1]+Integer.valueOf(toCarry);/*increment the next value with the carried value */ | |
}else continue; | |
} | |
/* check if the first element > 9 and extend the array */ | |
int temp=array.length; | |
if(array[0]>9){ | |
last=array[n].toString(); /* get the current value in string*/ | |
strlen=last.length(); | |
String remainder=last.substring(strlen-1,strlen);/* get the remainder */ | |
array[n]=Integer.valueOf(remainder);/*assign the remainder to the current value */ | |
temp=temp+strlen-1; | |
Integer[] arrayCopy=new Integer[temp]; | |
for(int j=0;j<strlen;j++){ | |
arrayCopy[j]=Integer.valueOf(Character.toString(last.charAt(j))); | |
} | |
System.arraycopy(array,0,arrayCopy,strlen-1,array.length); /* extend the array */ | |
for(Integer k:arrayCopy) | |
System.out.print(k+","); | |
} | |
else{ | |
for(Integer k:array) | |
System.out.print(k+","); | |
} | |
System.out.println(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment