public class Reversing {
public static void main(String[] args) {
String str = "Nitin";
// If str is quite small then StringBuilder will be quite slow as compare
// to custom approach given below. For large values StringBuilder is quite
// fast than the custom approach below.
long start = System.nanoTime();
StringBuilder sb1 = new StringBuilder(str);
sb1.reverse();
System.out.println("Time Taken : " + (System.nanoTime() - start));
start = System.nanoTime();
int len = str.length();
StringBuilder sb = new StringBuilder(len);
int j = 0;
for(int i = (len/2-1); i >= 0; i--) {
sb.append(str.charAt(i));
sb.insert(j, str.charAt(len-j-1));
j++;
}
sb.insert((len/2), str.charAt((len/2)));
System.out.println("Time Taken : " + (System.nanoTime() - start));
System.out.println(sb);
}
}
Or better use below way to save memory & have better performance -
public static void main(String[] args) {
String str = "Nitin";
// If str is quite small then StringBuilder will be quite slow as compare
// to custom approach given below. For large values StringBuilder is quite
// fast than the custom approach below.
long start = System.nanoTime();
StringBuilder sb1 = new StringBuilder(str);
sb1.reverse();
System.out.println("Time Taken : " + (System.nanoTime() - start));
start = System.nanoTime();
int len = str.length();
StringBuilder sb = new StringBuilder(len);
int j = 0;
for(int i = (len/2-1); i >= 0; i--) {
sb.append(str.charAt(i));
sb.insert(j, str.charAt(len-j-1));
j++;
}
sb.insert((len/2), str.charAt((len/2)));
System.out.println("Time Taken : " + (System.nanoTime() - start));
System.out.println(sb);
}
}
Or better use below way to save memory & have better performance -