# The odd trick in the C language

• 2020-06-07 05:02:39
• OfStack

preface

When you learn C, you will always encounter a lot of eye-catching code, especially if you have written a few lines of code, and others only need a few lines of recursive implementation. Here's a summary of some of the more novice code in C. Let you have a "woc! To write like that!" The idea of base 2 recursion takes a detour.

Type 1: Recursion

Find the greatest common factor

Conventional writing method:

``````
int gcd(int m, int n)
{
int r;
if (m>n){r=m,m=n,n=r;}
r=n%m;
while (r!=0){
n=m;
m=r;
r=n%m;
}
return m;
}``````

SAO operation! Recursion!

``````
int gcd(int x, int y) {
return y?gcd(y,x%y):x;
}``````

The first time I saw this code, My reaction was black question mark face. Oh my god? You can still write it like this in division? wtf

Output the string in reverse order

Conventional writing method:

``````
char *reverse(char *str)
{
if( !str )           // Determines if the input string is an empty string
{
return NULL;         // Returns if the string is empty NULL
}

int len = strlen(str);
if( len > 1 )
{
char ctemp =str[0];
str[0] = str[len-1];
str[len-1] = '\0';   //  The last 1 Characters are not processed the next time the recursion occurs
reverse(str+1);     //  Recursive calls
str[len-1] = ctemp;
}

return str;
}``````

Recursion!

``````
void reverse(char *x)
{
if(*x){          // If the character variable is 0 ( ascii Code values for 0 Not a number '0' ) is not entered
fun(x+1);     // Recursive calls
printf("%c",*x);  // Output a single character
}
}``````

Isn't that a bit of a stack!

Type 2: Base 2!

Exchange the values of the two variables

Conventional writing method:

``````
int temp = a;
a = b;
b = temp;``````

Three lines of code, using a median. Then the xor in base 2 would not use the third value and would only have 1 line of code.

Write in base 2:

[

a ^= b ^= a ^= b;

]

Specific time complexity of both, there is no in-depth understanding.

The number of 'ones' in base 2

Conventional writing method:

``````
int v; // The variable being evaluated
int count=0; // To calculate 2 Into the system ' 1' The number of
while(v != 0){
if(v%2 ==1)
count++;
v /= 2;
}``````

The counted variable is added to 2, and count plus 1 if the remainder is 1.

Write in base 2:

``````
int v=9;  // The variable being counted
int count; // statistical 2 Into the system ' 1' The number of
for(count=0; v; count++) {
v &= v-1;
}``````

Taking advantage of the properties of the base 2 operator, manipulating base 2 makes the method simpler and more rational.

To be continue...

Related articles: