CodeWars 쉰 일곱 번째 문제

Updated:

Reverse or rotate?

public static String revRot(String strng, int sz) {

    if(strng.length() == 0 || sz < 1) {
        return "";
    }

    String reverse = "";

    while(strng.length() >= sz) {

        reverse += reverseOrRotate(sum(strng.substring(0,sz)),strng.substring(0,sz));

        strng = strng.substring(sz);
    }

    return reverse;
}

private static String reverseOrRotate(long sumFront, String strng) {

    if(sumFront % 2 == 0) {
        return new StringBuffer(strng).reverse().toString();
    }

    return strng.substring(1) + strng.substring(0,1);
}

private static long sum(String strng) {

    long sum = 0;

    while(strng.length() > 0) {
        sum += Integer.parseInt(strng.substring(0,1));
        strng = strng.substring(1);
    }

    return sum;
}
  • Best 코드와 같은 알고리즘.
  • 위의 코드가 리펙토링이 필요한 것 같아서 변경해 보았다.
  • 변수명과 메소드명을 확연하게 변경
  • 반복되는 코드를 하나로 추출
  • 한 메소드에서 2가지 하는 일을 두 개의 메소드로 변경
public static String revRot(String strng, int sz) {

    String result = "";

    while(strng.length() >= sz && strng.length() !=0) {

        String cubes = strng.substring(0,sz);

        result += isEven(sumCubes(cubes)) ? reverse(cubes) : rotate(cubes);

        strng = strng.substring(sz);
    }

    return result;
}

public static boolean isEven(int sumCubes) {
    return sumCubes % 2 == 0;
}

private static String reverse(String cubes) {
    return new StringBuffer(cubes).reverse().toString();
}

private static String rotate(String cubes) {
    return cubes.substring(1) + cubes.substring(0,1);
}

private static int sumCubes(String cubes) {

    int sum = 0;

    while(cubes.length() > 0) {
        sum += Integer.parseInt(cubes.substring(0,1));
        cubes = cubes.substring(1);
    }

    return sum;
}