C language operators practice

1.unsigned int reverse_bit (unsigned int value) ;
return value of the function value is a value of the bit inverted pattern from left to right.

#define  _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>
unsigned int reverse_bit(unsigned int value)
{
    int ret = 0;
    int tmp = 0;
    for (int i=0; i < 32; i++)
    {
        ret = ret << 1;//左移一位,保存前一位
        tmp = value & 1;//取出最后一位
        value = value >> 1;//值右移, 取下一位
        ret = ret | tmp;//最后一位赋给ret
     }
	   return ret;
}
int main()
{
    int input = 0;
    printf("请输入一个数字:\n");
    scanf("%d", &input);
    printf("%u\n",reverse_bit(input));
    system("pause");
    return 0;
}


2. Do not use (a + b) / 2 In this manner, an average of two numbers.

#include<stdio.h>
#include<stdlib.h>
int Avg_Num(int a, int  b)
{
	int num = 0;
	num = (b - a) / 2 + a;
	return num;
}
int main()
{
	int a, b;
	printf("请输入两个数字:\n");
	scanf_s("%d %d", &a, &b);
	printf("%d\n",Avg_Num(a, b));
	system("pause");
	return 0;
}

It is equivalent to right shift by 2 operator

int Avg_Num(int a, int  b)
{
	return ((a&b) + ((a^b) >> 1));
}

3. programming:
a set of data in a number appears only once.
All other numbers are in pairs.
Look for this number. (Using bit operation)
0 exclusive of any number or any number,
the same number of XOR 0

int Seek_num(int arr[],int len)
{
	int ret = 0;
	for (int i = 0; i < len; i++)
	{
		ret = ret^arr[i];
	}
	return ret;
}
int main()
{
	int arr[] = { 2, 2, 3, 4, 5, 7, 3, 5, 4 };
	int len = 0;
	len = sizeof(arr) / sizeof(arr[0]);
	printf("%d\n",Seek_num(arr,len));
	system("pause");
	return 0;
}

4. There is a character array of content: "student a am i",
the contents of the array you read "i am a student".
Requirements:
You can not use the library functions.
Only a limited number of open spaces (regardless of the number of space and character string length).
See the problem first analysis should be used twice in reverse order, first get "i ma a tneduts", then after each space-separated string again in reverse order to get "i am a student"

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void reverse(char* start, char* end)
{
	while (start < end)
	{
		char tmp = *start;
		*start = *end;
		*end = tmp;
		start++;
		end--;
	} 
}

void str_reverse(char* str)
{	
	int len = strlen(str);
	reverse(str, str + len - 1);  //全部逆置
	while (*str != '\0')
	{
		char* pos = str;
		while ((*str != ' ') && (*str != '\0'))
		{
			str++;
		}
		reverse(pos, str - 1);    //每个单词的逆置
		if (*str != '\0')
		{
			str++;
		}
	}
}

int main()
{
	char str[] = "student a am i";
	printf("原字符串为:%s\n", str);
	str_reverse(str);
	printf("翻转后的字符串为:%s\n", str);

	system("pause");
	return 0;
}

Published 60 original articles · won praise 23 · views 3334

Guess you like

Origin blog.csdn.net/weixin_44945537/article/details/99569337