Count total set bits in all numbers from 1 to n

本文介绍了一种高效算法来计算从1到n的所有整数中二进制表示的1的总数,并通过递归方式解决了该问题。对于特殊形式的n,给出了直接计算公式。

reference: 

http://www.geeksforgeeks.org/count-total-set-bits-in-all-numbers-from-1-to-n/


Problem Definition:

Given a positive integer n, count the total number of set bits in binary representation of all numbers from 1 to n.

Examples:

Input: n = 3
Output:  4

Input: n = 6
Output: 9


Solution:

If the input number is of the form 2^b -1 e.g., 1,3,7,15.. etc, the number of set bits is b * 2^(b-1). This is because for all the numbers 0 to (2^b)-1, if you complement and flip the list you end up with the same list (half the bits are on, half off).

If the number does not have all set bits, then some position m is the position of leftmost set bit. The number of set bits in that position is n – (1 << m) + 1. The remaining set bits are in two parts:

1) The bits in the (m-1) positions down to the point where the leftmost bit becomes 0, and
2) The 2^(m-1) numbers below that point, which is the closed form above.

An easy way to look at it is to consider the number 6:

0|0 0
0|0 1
0|1 0
0|1 1
-|–
1|0 0
1|0 1
1|1 0

The leftmost set bit is in position 2 (positions are considered starting from 0). If we mask that off what remains is 2 (the "1 0" in the right part of the last row.) So the number of bits in the 2nd position (the lower left box) is 3 (that is, 2 + 1). The set bits from 0-3 (the upper right box above) is 2*2^(2-1) = 4. The box in the lower right is the remaining bits we haven't yet counted, and is the number of set bits for all the numbers up to 2 (the value of the last entry in the lower right box) which can be figured recursively.


Code:

// Returns count of set bits present in all numbers from 1 to n
unsigned int countSetBits(unsigned int n)
{
   // Get the position of leftmost set bit in n. This will be
   // used as an upper bound for next set bit function
   int m = getLeftmostBit (n);
 
   // Use the position
   return _countSetBits (n, m);
}
 
unsigned int _countSetBits(unsigned int n, int m)
{
    // Base Case: if n is 0, then set bit count is 0
    if (n == 0)
       return 0;
 
    /* get position of next leftmost set bit */
    m = getNextLeftmostBit(n, m);
 
    // If n is of the form 2^x-1, i.e., if n is like 1, 3, 7, 15, 31,.. etc, 
    // then we are done. 
    // Since positions are considered starting from 0, 1 is added to m
    if (n == ((unsigned int)1<<(m+1))-1)
        return (unsigned int)(m+1)*(1<<m);
 
    // update n for next recursive call
    n = n - (1<<m);
    return (n+1) + countSetBits(n) + m*(1<<(m-1));
}


c++题解,代码没有注释,可从上网查询,输出必须符合样例,本题有8个测试点,请得满分。 T-2 Breaking Through 分数 35 作者 陈越 单位 浙江大学 In a war game, you are given a map consists of n×n square blocks. Starting from your current block, your task is to conquer a destination block as fast as you can. The difficulties are not only that some of the blocks are occupied by enemies, but also that they are shooting in some directions. When one is shooting in some direction, the whole row/column in that direction will be covered by fire, unless there is another enemy blocking the way. You must make sure that you are not shot on the way to your destination. However, it is very much likely, at the very beginning, that this task is impossible. So you must follow the following instructions: Step 1: find the shortest path from the starting block to the destination, avoiding all the enemy blocks. The path length is the number of blocks on the way, not including the starting block. If this path is not unique, select the smallest index sequence – that is, all the blocks are indexed from 1 to n 2 , starting from the upper-left corner, and row by row till the lower-right corner. An index sequence is an ordered sequence of the block indices from the starting block to the destination. One sequence { s,u 1 ​ ,⋯,u k ​ ,d } is said to be smaller than { s,v 1 ​ ,⋯,v k ​ ,d }, if there exists 1≤p≤k such that u i ​ =v i ​ for i<p and u p ​ <v p ​ . Step 2: if some of the blocks along the selected shortest path is covered by fire, conquer and clear the nearest reachable enemy block that are firing at the path (in case that such a block is not unique, take the one with the smallest index). Then take that block as the starting position, goto step 1. Keep in mind that you must always make sure that you are not shot on the way. If step 2 is impossible, then the game is over. Otherwise, keep going until you finally conquer the destination. Input Specification: Each input file contains one test case. For each case, the first line contains a positive integer n (3≤n≤100), which is the size of the map. Then n lines follow, each gives n numbers. Each number describes the status of the corresponding block: 0 means the block is clear; 1, 2, 3, or 4 means the block is occupied by an enemy, who will shoot toward up, down, left, and right, respectively; 5 means the block is your starting position; 6 means the block is your destination. All the numbers in a line are separated by a space. Note: You can never cross any of the boundaries of the map. When an enemy is shooting from block A in direction B, every block starting from A in direction B will be covered by fire, untill the boundary is reached, or another enemy block is encountered. The enemies will never kill each other. Only you will get killed if you step into a block that is covered by fire. It is guaranteed that there is no more than n enemy blocks, and your starting position is not on fire. Output Specification: Print in a line the path length for you to reach the last block from your starting position, and the block number. The two numbers must be separated by 1 space. In the next line, print Win if the destination is reached, or Lose if not. Sample Input 1: 6 6 2 0 0 0 0 0 0 0 0 0 0 0 4 0 0 0 0 0 0 0 0 1 0 0 0 0 3 5 0 4 0 0 0 0 0 Sample Output 1: 10 1 Win Hint: The movements are shown by the following figures 14. Figure 1 shows how the blocks are numbered. Figure 2 shows the initial status of the map, where the player’s position is green, enemy blocks are black, and red blocks are covered by fire. At the very beginning the shortest path was 29->30->24->18->12->11->10->9->8->7->1, but the path was covered by fire shooting from blocks 23, 14 and 2. Since the enemy block 23 is the nearest reachable one, it was cleared with path length 1. Now starting from block 23, the shortest path was 23->17->11->10->9->8->7->1, but the path was covered by fire shooting from blocks 14 and 2. Since the enemy block 14 is covered by fire from block 2, taking block 2 now is the only option. So next, block 2 is cleared with path length 8 (crossing the destination). Finally we can get to the destination from block 2 to 1. Sample Input 2: 4 5 0 2 0 0 0 0 0 0 1 0 0 4 0 6 3 Sample Output 2: 6 3 Lose Hint: The movements are shown by the following figures 5~8. Figure 5 shows how the blocks are numbered. Figure 6 shows the initial status of the map. At the very beginning the shortest path was 1->2->6->7->11->15, but the path was covered by fire shooting from blocks 3, 10, 13 and 16. Since the enemy block 10 is the nearest reachable one, it was cleared with path length 3. Now starting from block 10, the shortest path was 10->11->15, but the path was covered by fire shooting from blocks 3, 13 and 16. Since the enemy blocks 13 and 16 are covered by fire from each other, taking block 3 now is the only option. So next, block 3 is cleared with path length 3. Now it is clear that there is no way to conquer the destination, since block 15 is fired by 13 and 16, yet we cannot clear any of them without getting fired. Hence the last block we can reach is 3. steps2.png 代码长度限制 16 KB 时间限制 400 ms 内存限制 64 MB 栈限制 8192 KB
08-23
**项目名称:** 基于Vue.js与Spring Cloud架构的博客系统设计与开发——微服务分布式应用实践 **项目概述:** 本项目为计算机科学与技术专业本科毕业设计成果,旨在设计并实现一个采用前后端分离架构的现代化博客平台。系统前端基于Vue.js框架构建,提供响应式用户界面;后端采用Spring Cloud微服务架构,通过服务拆分、注册发现、配置中心及网关路由等技术,构建高可用、易扩展的分布式应用体系。项目重点探讨微服务模式下的系统设计、服务治理、数据一致性及部署运维等关键问题,体现了分布式系统在Web应用中的实践价值。 **技术架构:** 1. **前端技术栈:** Vue.js 2.x、Vue Router、Vuex、Element UI、Axios 2. **后端技术栈:** Spring Boot 2.x、Spring Cloud (Eureka/Nacos、Feign/OpenFeign、Ribbon、Hystrix、Zuul/Gateway、Config) 3. **数据存储:** MySQL 8.0(主数据存储)、Redis(缓存与会话管理) 4. **服务通信:** RESTful API、消息队列(可选RabbitMQ/Kafka) 5. **部署与运维:** Docker容器化、Jenkins持续集成、Nginx负载均衡 **核心功能模块:** - 用户管理:注册登录、权限控制、个人中心 - 文章管理:富文本编辑、分类标签、发布审核、评论互动 - 内容展示:首页推荐、分类检索、全文搜索、热门排行 - 系统管理:后台仪表盘、用户与内容监控、日志审计 - 微服务治理:服务健康检测、动态配置更新、熔断降级策略 **设计特点:** 1. **架构解耦:** 前后端完全分离,通过API网关统一接入,支持独立开发与部署。 2. **服务拆分:** 按业务域划分为用户服务、文章服务、评论服务、文件服务等独立微服务。 3. **高可用设计:** 采用服务注册发现机制,配合负载均衡与熔断器,提升系统容错能力。 4. **可扩展性:** 模块化设计支持横向扩展,配置中心实现运行时动态调整。 **项目成果:** 完成了一个具备完整博客功能、具备微服务典型特征的分布式系统原型,通过容器化部署验证了多服务协同运行的可行性,为云原生应用开发提供了实践参考。 资源来源于网络分享,仅用于学习交流使用,请勿用于商业,如有侵权请联系我删除!
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值