算法训练 二进制数数

烂漫一生 提交于 2019-12-10 10:18:59

问题描述

  给定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 Main {
      public static void main(String[] args) {
          Scanner sc=new Scanner(System.in);
          int n=sc.nextInt();
          int m=sc.nextInt();
          int d=n;
          int count=0;
          String a[]=new String[m-n+1];
          for(;n<=m;n++){
              a[n-d]=Integer.toBinaryString(n);
              char c[]=a[n-d].toCharArray();
              for(int i1=0;i1<c.length;i1++) {
                  if('1'==c[i1]) {
                      count++;
                  }
              }
          }
          System.out.println(count);
      }
}

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!