repeatEnd function in Java (CodingBat Solution)

Problem 2:
Given a string and an int n, return a string made of n repetitions of the last n characters of the string. You may assume that n is between 0 and the length of the string, inclusive.

repeatEnd("Hello", 3) → "llollollo"
repeatEnd("Hello", 2) → "lolo"
repeatEnd("Hello", 1) → "o"

Solution:
package com.nextgen4it.problems;
public class repeatEndfunction {
                public String repeatEnd(String str, int n)

                {
                                String res = str.substring(str.length() - n);
                                for (int i = 1; i < n; i++)
                                                res = res + str.substring(str.length() - n);
                                return res;
                }
                public static void main(String[] args) {
                                repeatEndfunction r=new repeatEndfunction();
                                System.out.println(r.repeatEnd("Hello", 3));
                }
}

Output :

llollollo



EmoticonEmoticon