topic:
Programming implementation : How many bits (bits) are different in the binary representation of two int (32-bit) integers m and n ?
Input example:
1999 2299
Example output: 7
=========================================================================
Ideas:
general idea:
After XORing m and n , there are as many 1s as there are differences , and then calculate how many 1s there are in binary
(1). Write a function: number_of_1() to calculate how many 1s there are in binary .
(2). In the main function , pass the result of m ^ n (m XOR n) as a parameter to the number_of_1() function
first step:
Write a function: number_of_1() to calculate how many 1s there are in binary :
(1). Function return value: int , returns the number of 1 in binary ;
Function parameter: int m
(2). Set the counter count to count the number of 1 in the two-level system
(3). Use while loop , loop statistics, continue to loop as long as m is not 0
(4). Use m = m & (m - 1); --Remove the rightmost 1 in the binary, and then assign it to m itself ,
Remove a 1 , and the counter count is ++ .
Implementation code:
#include <stdio.h> //编写函数: int number_of_1(int m) //函数返回值:int ; 函数形参:int m { //设置计数器: int count = 0; //使用while循环 while (m) //如果m不为0,就说明二进制中还有1,则继续循环 { //使用公式: m = m & (m - 1); //去掉最右边的1 count++; //计数器++ } } int main() { return 0; }
Realize the picture:
Step two:
main function:
(1). Input two parameters : m and n
(2). Pass the result of m ^ n (m XOR n) as a parameter to the number_of_1() function ,
and use a variable to receive the return value
(3). Print return value
Implementation code:
#include <stdio.h> //编写函数: int number_of_1(int m) //函数返回值:int ; 函数形参:int m { //设置计数器: int count = 0; //使用while循环 while (m) //如果m不为0,就说明二进制中还有1,则继续循环 { //使用公式: m = m & (m - 1); //去掉最右边的1 count++; //计数器++ } } int main() { //输入两个数: int m = 0; int n = 0; scanf("%d %d", &m, &n); //异或:相同为0,相异为1 int ret = number_of_1(m ^ n); //打印: printf("%d", ret); return 0; }
Realize the picture:
Final code and implementation effect
Final code:
#include <stdio.h> //编写函数: int number_of_1(int m) //函数返回值:int ; 函数形参:int m { //设置计数器: int count = 0; //使用while循环 while (m) //如果m不为0,就说明二进制中还有1,则继续循环 { //使用公式: m = m & (m - 1); //去掉最右边的1 count++; //计数器++ } } int main() { //输入两个数: int m = 0; int n = 0; scanf("%d %d", &m, &n); //异或:相同为0,相异为1 int ret = number_of_1(m ^ n); //打印: printf("%d", ret); return 0; }
Realize the effect: