Advertisement
Saltor

Untitled

Dec 27th, 2013
348
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.94 KB | None | 0 0
  1. // the only variables used are the char[] representing the string and
  2. // the iterator variable i
  3. public static void reverseInPlace(char[] str) {
  4.     // for each character in the first half of the string, rounded down
  5.     for(int i = 0; i < str.length / 2; i++) {
  6.         // if opposite characters are equal, no transformation is needed
  7.         // if the characters differ, swap them
  8.         if(str[i] != str[str.length - i - 1]) {
  9.             // this bit-xoring trick works as long as the values being
  10.             // swapped are not equivalent
  11.             str[i] ^= str[str.length - i - 1];
  12.             str[str.length - i - 1] ^= str[i];
  13.             str[i] ^= str[str.length - i - 1];
  14.         }
  15.     }
  16. }
  17.  
  18. public static void main(String[] args) {
  19.     String s = "abcdefg";
  20.     char[] arr = s.toCharArray();
  21.     System.out.println("arr: " + new String(arr));
  22.     reverseInPlace(arr);
  23.     System.out.println("arr rev: " + new String(arr));
  24. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement