Article Directory
The Magic Number
Description Title
string into digital numbers even bit inversion, and the result is output after inversion.
Example 1:
Enter: "1234" |
---|
Output: "1432" |
Description: The first bit is an even number 2, 4, so after turning it over, to give 1432 |
Example 2:
Enter: "12346" |
---|
Output: "16342" |
Description: The first bit is an even number, 4, 5, so after turning it over, to give 16342 |
Remarks :
Digital length <= 10 . 7 , not including the number 0 |
---|
Problem-solving ideas: the use bit arithmetic logic and (&), the solution of this question is very good. Alphanumeric str [i] is converted to an integer
str [i] - '0' , '0' is the ASCII code 48. The even-numbered & 1 == 0, empathy even number of characters & 1 == 0. I know this to solve this problem on easy friends.
Here is my code:
void change(char *str)
{
int i = 0;
int j = 0;
while(str[j]!='\0')
j++;
j--;
while(i<j)
{
if(!(str[i]&1))
{
if(!(str[j]&1))
{
str[i] = str[i]^str[j];
str[j] = str[i]^str[j];
str[i] = str[i]^str[j];
i++;
j--;
}
else
j--;
}
else
i++;
}
}