T
T
testerpe2021-09-19 13:03:27
Java
testerpe, 2021-09-19 13:03:27

OutOfMemoryError: Tried to solve a problem with Codewars, but got this error?

Each word in the text must be encoded according to the given rules:
• The first letter must be converted to its ASCII code;
• The second letter must be replaced by the last letter.

I wrote this code, but it fails with an OutOfMemoryError. What is wrong and how to fix it?

public static String encryptThis(String text) {
        String[] words = text.split(" ");
        StringBuilder builder = new StringBuilder();
        for (int i = 0; i < words.length; i++) {
            char[] letters = words[i].toCharArray();
            StringBuilder transformedWord = new StringBuilder();
            char secondLetter = letters[1];
            char lastLetter = letters[letters.length - 1];
            transformedWord
                    .append((byte) letters[0])
                    .append(lastLetter);
            int k = 2;
            while (k < letters.length - 1) {
                transformedWord.append(letters[k]);
            }
            transformedWord.append(secondLetter);
            builder.append(transformedWord.toString());
        }
        builder.deleteCharAt(builder.length() - 1);
        return builder.toString();
    }

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey_USB, 2021-09-19
@Sergey_USB

Just take the first character s.charAt(0) and replace it with ASCII
Take the last s.charAt(length-1)
Take the rest of s.charAt(1) and add a new word from it.
I would do this - all in one action

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question