I got some problem. I have two char arrays (for ex. char[] number1 = {‘1′,’1′,’1′,’1’}, and char[] number2 {‘2′,’2’}). And now I want to return array with same length what number1 is, but in indexes on the left where add ‘0’ (for ex. in this case => {‘0′,’0′,’2′,’2’}
I try something like this:
JavaScript
x
public static char[] whichShorter(char[] first,char[] secend){
if(first.length >= secend.length) return secend;
else return first;
}
public static char[] whichLonger(char[] first,char[] secend){
if(first.length >= secend.length) return first;
else return secend;
}
public static char[] makeEqual(char[] first, char[] secend){
char[] longer = whichLonger(first,secend);
char[] shorter = whichShorter(first, secend);
char[] addZero = new char[longer.length];
for (int i = shorter.length; i >0 ; i--) {
addZero[i]=shorter[i-1];
}
for (int i = 0; i < addZero.length ; i++) {
if(addZero[i]==(char) 0) addZero[i]='0';
}
return addZero;
}
I guess its not hard at all, but im trying hard and there no effect (I try to draw on paper first, everything).
Advertisement
Answer
You can do:
JavaScript
Stream<Character> leadingZeros = IntStream.range(0, number1.length - number2.length)
.mapToObj(i -> '0');
Stream<Character> originalChars = IntStream.range(0, number2.length)
.mapToObj(i-> number2[i]);
Character[] newNumber2 = Stream.concat(leadingZeros, originalChars).toArray(Character[]::new);
System.out.println(Arrays.toString(newNumber2));
Input 1:
JavaScript
char[] number1 = {'1','1','1','1'};
char[] number2 = {'2','2'};
Output 1:
JavaScript
[0, 0, 2, 2]
Input 2:
JavaScript
char[] number1 = {'1','1','1','1'};
char[] number2 = {'2','2', '2', '2', '2'};
Output 2:
JavaScript
[2, 2, 2, 2, 2]