minatoruan
BAN USERI do not think I should care about the zero on each bar code. if a bar code differs another with one or two bits, its number of 1 is larger one or two than the another. This is my solution.
- Count 1 on each bar code, then store into array of integer with each item.
- Push item 1 into a bag because there is at least one bag
- Loop on the rest of bar code
- Test one with each bar code in the existing bags by comparing the number of 1 with being not two larger.
- If there is no bag left, create new bag.
import java.util.Stack;
public class HelloWorld {
public static void main(String[] args) {
HelloWorld hw = new HelloWorld();
System.out.printf(hw.insertMissingNumber("99799899910011002"));
}
public String insertMissingNumber(String str) {
int[] array = new int[str.length()];
char[] digits = str.toCharArray();
for(int index = 0; index < str.length(); index++) {
array[index] = digits[index] - '0';
}
int digitLength = 1;
while (digitLength < digits.length + 1) {
int position = 0;
int tempLength = digitLength;
while (position + tempLength < digits.length) {
Stack<Integer> stack1 = getNextValue(array, position, tempLength, 1);
Stack<Integer> stack2 = getNextValue(array, position, tempLength, 2);
if(getLengthMatched(array, position + tempLength, stack2) >= tempLength) {
return String.format("%s%s%s",
str.substring(0, position + tempLength),
getString(stack1),
str.substring(position + tempLength));
}
int lengthMatched = getLengthMatched(array, position + tempLength, stack1);
if(lengthMatched >= tempLength) {
position = position + tempLength;
tempLength = lengthMatched;
continue;
}
break;
}
digitLength++;
}
return str;
}
private Stack<Integer> getNextValue(int[] array, int position, int length, int step) {
Stack<Integer> stack = new Stack<Integer>();
int last = position + length - 1;
do {
stack.push((array[last] + step) % 10);
step = (array[last] + step) / 10;
last--;
} while (last >= position);
if(step > 0) {
stack.push(step);
}
return stack;
}
private int getLengthMatched(int[] array, int position, Stack<Integer> stack) {
int len = 0;
while(stack.isEmpty() == false) {
if(array[position] == stack.pop()) {
position++;
len++;
} else {
break;
}
}
return len;
}
private String getString(Stack<Integer> stack){
int val = 0;
while (stack.isEmpty() == false) {
val = val * 10 + stack.pop();
}
return String.format("%s", val);
}
}
Repannarrathjen, Employee at 247quickbookshelp
Hello, My name is Anna and I am a medical records technician with 2 years of experience and achievements. I ...
Sorry, it's wrong :)
- minatoruan October 01, 2013We should consider the position of the number of 1 if there is more than 3 of 1