鱼C论坛

 找回密码
 立即注册
查看: 986|回复: 1

一段连续数字中,所有数字转化为二进制后,含有'1'的个数相加

[复制链接]
发表于 2018-5-25 08:56:23 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
Given two numbers: 'left' and 'right' (1 <= 'left' <= 'right' <= 200000000000000) return sum of all '1' occurencies in
binary representations of numbers between 'left' and 'right' (including both)

Example:
countOnes 4 7 should return 8, because:
4(dec) = 100(bin), which adds 1 to the result.
5(dec) = 101(bin), which adds 2 to the result.
6(dec) = 110(bin), which adds 2 to the result.
7(dec) = 111(bin), which adds 3 to the result.
So finally result equals 8.
WARNING: Segment may contain billion elements, to pass this kata, your solution cannot iterate through all numbers in the segment!

这段数字有可能有数十亿,遍历所有数这种方法不能用,时间会超时,这是codewars碰到的题
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

发表于 2018-5-25 09:02:24 | 显示全部楼层
lz思考一下:
1 一个2位的二进制数含有1的个数有几种情况?
2 一个3位,4位,5位,n位的二进制数含有1的个数有几种情况?
3 题目中给定的是一个连续的整数范围,在二进制中是不是也是连续的?

如果想清楚了这些问题,我想应该可以有一种思路去解这个问题了
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2024-3-28 20:38

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表