int countbit(unsigned int x) {
int i;
int cnt = 0;
int mask = 0x00000001;
for (i = 0; i < sizeof(unsigned int) << 3; i++) {
if (x & mask)
cnt++;
x >>= 1;
}
return cnt;
}unsigned int multiply(unsigned int x, unsigned int y) {
int i;
int sum = 0;
int mask = 1;
for (i = 0; i < 32; i++) {
if (y & mask)
sum += x << i;
y >>= 1;
}
return sum;
}unsigned int rotate_right(unsigned int x, int n) {
int i;
int mask = 0x80000000;
for (i = 0; i < n; i++) {
if (x & 1) {
x >>= 1;
x |= mask;
} else
x >>= 1;
}
return x;
}1. countbit
#include <stdio.h>
int countbit(unsigned int x){
int count = 0;
while (x != 0) {
count += x & 1;
x >>= 1;
}
return count;
}
int main(void){
int n;
scanf("%d", &n);
printf("%d", countbit(n));
}
2. multiply
#include <stdio.h>
unsigned int multiply(unsigned int x, unsigned int y){
unsigned int res = 0;
while (y > 0) {
int last = y & 1;
if (last) {
res += x;
}
x <<= 1;
y >>= 1;
}
return res;
}
int main(void){
unsigned int x, y;
scanf("%d", &x);
scanf("%d", &y);
printf("%d", multiply(x, y));
}
3. rotate_right
#include <stdio.h>
unsigned int rotate_right(unsigned int x, int rol_num){
unsigned int y = x;
printf("x: %x\n", x);
y <<= 32 - rol_num;
x >>= rol_num;
unsigned int res = x | y;
printf("res: %x\n", res);
}
int main(void){
unsigned int n;
scanf("%d", &n);
printf("n: %x\n", n);
rotate_right(n, 16);
}
int countbit(unsigned int x)
{
int cnt = 0;
while(x != 0)
{
x &= (x - 1);
cnt++;
}
return cnt;
}自己做的第三题答案:
#include<stdio.h>
unsigned int roat_right(unsigned int x, int n)
{
unsigned int mask = 0x00000001, i, y, N = 4 * n;
for(i = 1; i <= N; i++){
y = x & mask;
x >>= 1;
if(y == 1)
x += y << 31;
}
return x;
}
int main(void)
{
unsigned int x = 0xdeadbeef;
printf("%x\n", roat_right(x, 4));
return 0;
}如果您有建设性意见,哪怕只是纠正一个错别字,也请不吝赐教,您留下的姓名和email将会出现在本书前言的致谢中。再次感谢您的宝贵意见!