1 十进制转为N进制
#include <stdio.h>
#include <string.h>
void trans(unsigned int num, unsigned int r, char *buffer)
{
char tmp;
int i = 0;
if (r < 2) {
return;
}
while (num) {//num != 0
tmp = num % r;
if (tmp <= 9) buffer[i++] = '0' + tmp;
else buffer[i++] = 'A' + tmp - 10;
num /= r;
}
buffer[i] = '\0';
}
int main()
{
unsigned int num;
unsigned int r;
char buff[32] = {0};
while (1) {
scanf("%d %d", &num, &r);
trans(num, r, buff);
printf("0x%s", buff);//逆序输出
memset(buff, 0, sizeof(buff));
}
return 0;
}
2 ——————————————————————————
#include <stdio.h>
void fun(int x)
{
int falgs = 0;
while (x) {
x = x&(x-1);
++falgs;
}
printf("%d\n", falgs);
}
int main()
{
int a;
scanf("%d", &a);
fun(a);
return 0;
}
输入:9561 输出:7
每执行一次x = x&(x-1),会将x用二进制表示时最右边的一个1变为0,因为x-1将会将该位(x用二进制表示时最右边的一个1)变为0。
总之就是计算一个数的二进制的1的个数。