16 二进制数数
作者: Turbo时间限制: 1S章节: 基本练习(循环)
问题描述 :
给定L,R。统计[L,R]区间内的所有数在二进制下包含的“1”的个数之和。
如5的二进制为101,包含2个“1”。
输入说明 :
第一行包含2个数L,R
1<=L<=R<=100000;
输出说明 :
一个数S,表示[L,R]区间内的所有数在二进制下包含的“1”的个数之和。
输入范例 :
2 3
输出范例 :
3
import java.util.Scanner;
public class test_16 {
/**
* 16 二进制数数
*/
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String s = sc.nextLine();
String[] split = s.trim().split(" ");
int start = Integer.valueOf(split[0]);
int end = Integer.valueOf(split[1]);
int sum=0,temp=0;
for (int i = start; i <=end; i++) {
temp=numOneOfBCD(i);
if(temp!=0){
sum+=temp;
}
}
System.out.println(sum);
}
public static int numOneOfBCD(int n){
int count=0;
while(n>0){
if(n%2==1){
count++;
n/=2;
}else{
n/=2;
}
}
return count;
}
}