1

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:

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).

1
  • You forgot to mention your problem with the code you've included. Make sure you include any errors or issues you're having. Commented May 2, 2021 at 12:07

1 Answer 1

1

You can do:

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:

char[] number1 = {'1','1','1','1'};
char[] number2 = {'2','2'};

Output 1:

[0, 0, 2, 2]

Input 2:

char[] number1 = {'1','1','1','1'};
char[] number2 = {'2','2', '2', '2', '2'};

Output 2:

[2, 2, 2, 2, 2]
Sign up to request clarification or add additional context in comments.

1 Comment

thanks, I can use build in function etc, but I did it another way, but thanks a lot

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.