String Incrementer Java Coding Challenge | Edabit | How'd You Code That?

preview_player
Показать описание
String Incremented

In today’s challenge, you’re tasked with writing a method that increments a string to create a new string.
The rules of the challenge are:
* If the string ends with a number, the number should be incremented by 1.
* incrementString("foo099") ➞ "foo100"
* If the string doesn't end with a number, 1 should be added to the new string.
* incrementString("foo") ➞ "foo1"
* If the number has leading zeros, the amount of digits should be considered.
* incrementString("foobar0009") ➞ "foobar0010"

Song: Sunflower - Ikson (Vlog No Copyright Music)
Music promoted by Vlog No Copyright Music.
Рекомендации по теме
Комментарии
Автор

Thank you! But it seems to me that this algorithm has one significant downside – it cannot work with huge numbers like 921, 130, 992, 543, 244, 010, 066, 580, 394, 721 because this number cannot be fitted even in the variable of a long type (because we use Long.parseLong()...). So this solution fails some tests on Codewars with huge numbers. We have to try not use numbers "as numbers" in this case, instead we can think of the approach with an array of digits to which we append 1 and convert it to the string which then gets appended to the string of actual characters.

I've written this solution. It certainly can be optimised, so once I do it, I will update my comment again.
But you can take a look at this version so far:

import java.util.*;
import java.util.stream.*;
import java.text.NumberFormat;

public class Kata {
public static String incrementString(String str) {

if(str.length() == 0) return "1";

StringBuilder number = new StringBuilder();
StringBuilder chars = new StringBuilder();

int reverseCounter = str.length() - 1;
while (reverseCounter >= 0 && {

reverseCounter--;
}

// reverse this string because we have pushed the digits in a reverse order
number.reverse();
// append to chars the left part of the string
chars.append(str.substring(0, str.length() - number.length()));

List<Integer> digits = new ArrayList<>();
// fill the list with digits
-> d.length() > 0).forEach(d ->
int[] digitsArray = digits.stream().mapToInt(i -> i).toArray(); // convert the ArrayList into the plain array of integers

digitsArray = // increment by 1

if (number.length() == 0) return str + "1";

String digitsString = Arrays.stream(digitsArray)
.mapToObj(String::valueOf)


String result = chars.append(String.join("", digitsString)).toString();
return result;
}

private static int[] incrementArrayByOne(int[] array) {
for (int i = array.length - 1; i >= 0; i--) {
array[i] += 1;
if (array[i] == 10) {
array[i] = 0;
} else return array;
}
if (array.length > 0 && array[0] == 0) {
int[] newArray = new int[array.length + 1];
System.arraycopy(array, 0, newArray, 1, array.length);
newArray[0] = 1;
return newArray;
}

return array;
}
}

s.chernikovv