问题描述
给定L,R。统计[L,R]区间内的所有数在二进制下包含的“1”的个数之和。
如5的二进制为101,包含2个“1”。
输入格式
第一行包含2个数L,R
输出格式
一个数S,表示[L,R]区间内的所有数在二进制下包含的“1”的个数之和。
样例输入
2 3
样例输出
3
数据规模和约定
L<=R<=100000;
代码示例:
import java.util.Scanner;
public class 二进制数数 {
public static void main(String[] args) {
// 输入区间[L,R]
Scanner sc = new Scanner(System.in);
int l = sc.nextInt();
int r = sc.nextInt();
// 统计转换成二进制后包含 1 的个数和
int count = 0;
// 遍历区间内的数字
for (int i = l; i <= r; i++) {
int temp = i;
// 把数字转换成二进制
while (temp != 0) {
// System.out.println(temp % 2 + " " + temp);
// 如果转换成的二进制数字包含了 1 ,就累计次数加1
if (temp % 2 != 0)
count++;
temp /= 2;
}
}
System.out.println(count);
}
}