Reverse Given String Without Using Temporary Variable.
Example:
Input : hello
Output: olleh
Input : abcd
Output : dcba
Implementation
class ReverseStringWithoutUsingTemporaryVariable{
static String reverse(char []array){
int start = 0;
int end = array.length-1;
while(start < end){
array[start] ^= array[end];
array[end] ^= array[start];
array[start] ^= array[end];
start++;
end--;
}
return new String(array);
}
static String reverseUtil(String str){
//Boundary Condition
if(str == null || str.length() == 0)
return null;
return reverse(str.toCharArray());
}
public static void main(String... args){
String str = "hello";
String reverse = reverseUtil(str);
System.out.println(reverse);
}
}
Output: hello
Example:
Input : hello
Output: olleh
Input : abcd
Output : dcba
Implementation
class ReverseStringWithoutUsingTemporaryVariable{
static String reverse(char []array){
int start = 0;
int end = array.length-1;
while(start < end){
array[start] ^= array[end];
array[end] ^= array[start];
array[start] ^= array[end];
start++;
end--;
}
return new String(array);
}
static String reverseUtil(String str){
//Boundary Condition
if(str == null || str.length() == 0)
return null;
return reverse(str.toCharArray());
}
public static void main(String... args){
String str = "hello";
String reverse = reverseUtil(str);
System.out.println(reverse);
}
}
Output: hello
No comments:
Post a Comment