Problem description
Given L, R. Count the sum of the number of "1"s contained in the binary system of all the numbers in the [L,R] interval.
For example, the binary value of 5 is 101, which contains 2 "1"s.
Input format The
first line contains two numbers L,R.
Output format
A number S, which represents the sum of the number of "1" contained in the binary system of all the numbers in the [L,R] interval.
Sample input
2 3
Sample output
3
Data scale and agreement
L<=R<=100000;
Problem solution:
first convert all the numbers in the [L,R] interval into binary numbers in turn, and then obtain the characters of the binary numbers one by one, and judge whether it is '1', if it is temp++;
code show as below:
import java.util.ArrayList;
import java.util.Scanner;
public class BinaryOne {
public static void main(String[] args) {
int temp=0;
Scanner scanner=new Scanner(System.in);
int L=scanner.nextInt();
int R=scanner.nextInt();
for(int i=L;i<=R;i++) {
String string=two(i);//10000
for(int j=0;j<string.length();j++) {
char a=string.charAt(j);
if(a=='1') {
temp++;
}
}
}
System.out.println(temp);
}
public static String two(int a) {
ArrayList<String> list=new ArrayList();
while(a!=0) {
list.add(a%2+"");
a=a/2;
}
String two="";
for(int i=list.size()-1;i>=0;i--) {
two+=list.get(i);
}
return two;
}
}