Problem:
Given a string, return a "rotated right 2" version where the last 2 chars are moved to the start. The string length will be at least 2.
right2("Hello") → "loHel"
right2("java") → "vaja"
right2("Hi") → "Hi"
Solution:
public String right2(String str) { return str.substring(str.length()-2, str.length()) + str.substring(0, str.length()-2); }
Awesome webite
ReplyDeletepublic String right2(String str) {
ReplyDeleteif(str.length() <= 2){
return str;
}
final String lastTwoChar = str.substring(Math.max(0, str.length() - 2));
if(str.length() < 4){
return str.substring(1) + str.charAt(0);
}
return lastTwoChar + str.substring(0, str.length()- 2);
}
public String right2(String str) {
ReplyDeleteString lastTwo = str.substring(str.length()-2);
return lastTwo + str.substring(0, str.length()-2);
}