1、实现一个函数,可以左旋字符串中的k个字符。(ABCD左旋一个字符得到BCDA,ABCD左旋两个字符得到CDAB )
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
void left_remove(char* p, int n, int len)
{
int i = 0;
for (i = 0; i < n; i++)
{
int j = 0;
int tmp = p[0];
for (j = 0; j < len - 1; j++)
{
p[j] = p[j + 1];
}
p[len - 1] = tmp;
}
}
int main()
{
char p[] = "ABCD";
int n = 0;
int len = strlen(p);
printf("左旋前字符串为:>");
printf("%s\n", p);
printf("左旋几位:>");
scanf_s("%d", &n);
while (n<1 || n>len - 1)
{
if (n == len || n == 0)
{
printf("左旋后字符串为:>");
printf("%s", p);
return 0;
}
else
{
printf("输入有误!\n");
scanf_s("%d", &n);
}
}
left_remove(p, n, len);
printf("旋转后:%s\n", p);
system("pause");
return 0;
}
2、判断一个字符串是否为另外一个字符串旋转之后的字符串。
例如:给定s1 =AABCD和s2 = BCDAA,返回1;给定s1=abcd和s2=ACBD,返回0。
(AABCD左旋一个字符得到ABCDA,AABCD左旋两个字符得到BCDAA,AABCD右旋一个字符得到DAABC )
#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int Isswap(char *str, char *sub)
{
char *p = malloc(strlen(str) + strlen(str) + 1);
strcpy(p, str);
strcat(p, str);//strcat()函数是字符串拼接函数,结果为abcdefabcdef
if (strstr(p, sub) == NULL)//strstr()函数,参数为两个字符串,进行字符串循环比较,如果p中不存在sub字符串,则返回NULL
return 0;
return 1;
}
int main()
{
char arr[] = "abcdef";
char arr1[] = "cdefab";
int r = Isswap(arr, arr1);
if (r == 1)
printf("1.是\n");
else
printf("0.不是\n");
system("pause");
return 0;
}
3、一个数组中只有两个数字是出现一次,其他所有数字都出现了两次。找出这两个只出现一次的数字,编程实现(二进制异或)。
void find_num(int arr[], int len)
{
int i = 0;
int ret = 0;
int pos = 0;
int x = 0;
int y = 0;
for (i = 0; i < len; i++)
{
ret ^= arr[i];
}
for (i = 0; i < 32; i++)
{
if (1 == ((ret >> i) & 1))
{
pos = i;
break;
}
}
for (i = 0; i < len; i++)
{
if (1 == ((arr[i] >> pos) & 1))
{
x ^= arr[i];
}
else
y ^= arr[i];
}
printf("x=%d,y=%d\n", x, y);
}
int main()
{
int arr[] = { 1, 2, 3, 1, 2, 3, 4, 5 };
int sz = sizeof(arr) / sizeof(arr[0]);
find_num(arr, sz);
system("pause");
return 0;
}
4、喝汽水,1瓶汽水1元,2个空瓶可以换一瓶汽水,给20元,可以多少汽水。编程实现。
方法一:
#define _CRT_SECURE_NO_WARNINGS 1
#include <stdio.h>
#include<Windows.h>
int Drink_sum(int money, int price)
{
int sum = 0;
int temp = 0;
int ret = 0;
sum = money / price;
ret = sum;
while (ret / 2 != 0)
{
temp = ret;
ret = ret / 2;
sum += ret;
ret = temp % 2 + ret;
}
return sum;
}
int main()
{
int money = 0;
int price = 0;
printf("please enter money and price:\n");
scanf("%d %d", &money, &price);
int bottle = Drink_sum(money, price);
printf("%d元可以喝汽水%d瓶\n", money, bottle);
system("pause");
return 0;
}
方法二:
#include<stdio.h>
#include<windows.h>
int main()
{
int money = 20;
int total = money;
int empty = money;
while (empty >= 2)
{
total += empty / 2;
empty = empty / 2 + empty % 2;
}
printf("%d\n", total);
system("pause");
return 0;
}