试题 算法训练 二进制数数

Lan
Lan
2020-03-24 / 0 评论 / 789 阅读 / 正在检测是否收录...
温馨提示:
本文最后更新于2020年03月24日,已超过1585天没有更新,若内容或图片失效,请留言反馈。
资源限制
时间限制:1.0s   内存限制:256.0MB
问题描述
  给定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.*;

public class 二进制数数 {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Scanner sc = new Scanner(System.in);
		int n = sc.nextInt();
		int m = sc.nextInt();
		int nums = 0;
		for (int i = n; i <= m; i++) {
			String x = Integer.toBinaryString(i) + "";
			for (int j = 0; j < x.length(); j++) {
				char y = x.charAt(j);
				if (y == '1') {
					nums++;
				}
			}
		}
		System.out.println(nums);
	}

}


0

评论 (0)

取消