Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // the only variables used are the char[] representing the string and
- // the iterator variable i
- public static void reverseInPlace(char[] str) {
- // for each character in the first half of the string, rounded down
- for(int i = 0; i < str.length / 2; i++) {
- // if opposite characters are equal, no transformation is needed
- // if the characters differ, swap them
- if(str[i] != str[str.length - i - 1]) {
- // this bit-xoring trick works as long as the values being
- // swapped are not equivalent
- str[i] ^= str[str.length - i - 1];
- str[str.length - i - 1] ^= str[i];
- str[i] ^= str[str.length - i - 1];
- }
- }
- }
- public static void main(String[] args) {
- String s = "abcdefg";
- char[] arr = s.toCharArray();
- System.out.println("arr: " + new String(arr));
- reverseInPlace(arr);
- System.out.println("arr rev: " + new String(arr));
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement