reverse c string
CC150 1.1 reverse c string
void swap(char &a, char &b){
a = a^b;
b = a^b;
a = a^b;
}
void reverse(char *s){
if (!s) return s;
char * p = s;
char * q = s;
while(q) ++q;
--q;//move from null to the last char
while(p<q){
swap(*p++,*q--);
//std::swap(str[i], str[j])
}
}
class Solution {
public:
string reverseString(string s) {
int left = 0;
int right = s.size()-1;
while(left<right){
swap(s[left++],s[right--]);
}
return s;
}
};//16/07/04
- Note:a & b must be different to use XOR swap
- REF:
- https://en.wikipedia.org/wiki/XOR_swap_algorithm
- http://en.cppreference.com/w/cpp/language/operator_precedence
- http://stackoverflow.com/questions/3825668/c-c-checking-for-null-pointer