跟着鹏哥学编程,拿一个好offer。
今天的内容是对一些作业题目的总结,自己写一遍,加深印象。
1.写一个函数,统计返回参数中1的个数
这里我学习到三种算法,分别记录如下。
方法一代码:
int count_num_of_1(int n)
{
int count = 0;//计数变量
while (n)
{
if ((n % 2) == 1)
{
count++;
}
n /= 2;
}
return count;
}
方法二代码:
//15:1111 - n
//14:1110 - (n-1)
//n&(n-1) - 1110
//减去一位1
//如此重复,即可计算出n=15中所有1的个数
int count_num_of_1(int n)
{
int count = 0;
while (n)
{
n = n & (n - 1);
count++;
}
return count;
}
方法三代码:
//n=15:00000000000000000000000000001111
// 1 : 00000000000000000000000000000001
//1按位与上n,相同位为1,不同为零
int count_num_of_1(int n)
{
int count = 0;
for (int i = 0; i < 32; i++)
{
if ((n & (1 << i)) != 0)
{
count++;
}
}
return count;
}
2.两个int(32位)整数m和n的二进制表达中,有多少个位(bit)不同?
首先我们应该想到异或,因为两个整数按位异或,相同为零,不同为1。根据这个思路,我们可以先将两个数异或,可以得出两个数有多少位不同,即有几个1,然后根据前面求整数中有几个1的代码,得出两个整数中有多少位不同。代码如下:
int main()
{
//m=12:1100
//n=11:1011
// 2: 0010
// 3: 0011
//m^n : 0111
int m, n;
int count = 0;
scanf("%d %d",&m,&n);
int num = m^ n;
while (num)
{
num = num & (num - 1);
count++;
}
printf("%d",count);
return 0;
}
3.成组输入一个整数(2-20),然后输出一个×形状的正方形,如下:
//输入:5
//输出:
//*---*
//-*-*-
//--*--
//-*-*-
//*---*
//设行数为i,列数为j,当i=j时或i+j=4时,输出'*'
//否则输出空格
代码如下:
int main()
{
int n = 0;
while (scanf("%d",&n) == 1)
{
int i, j;
for (i = 0; i < n; i++)
{
for (j = 0; j < n; j++)
{
if (i == j)
printf("*");
else if ((i + j) == (n - 1))
printf("*");
else
printf(" ");
}
printf("\n");
}
}
return 0;
}
4.输入年份和月份,然后输出这个月有多少天。
代码如下:
#include <stdio.h>
int is_leap_year(int y)
{
if (((y % 4 == 0) && (y % 100 == 0)) || (y % 400 == 0))
return 1;
else
return 0;
}
int main()
{
int year;
int month;
int days[13] = { 0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
while (scanf("%d %d", &year, &month) == 2)
{
if ((is_leap_year(year) == 1) && (month == 2))
{
days[month]++;
}
printf("%d\n",days[month]);
}
return 0;
}