hackerrank Day 10: Binary Numbers

本文介绍了一个简单的C++程序,该程序用于找出给定十进制整数转换为二进制后的最大连续1的数量。通过迭代地右移位并检查最低位是否为1来计算连续1的数量,并更新最大连续1的计数。

Task 
Given a base-10 integer, n, convert it to binary (base-2). Then find and print the base-10 integer denoting the maximum number of consecutive 1's in n's binary representation.

Input Format

A single integer, n.

Constraints

 1 <= n <= 10^6

Output Format

Print a single base-10 integer denoting the maximum number of consecutive 1's in the binary representation of n.

Sample Input 1

5

Sample Output 1

1

Sample Input 2

13

Sample Output 2

2

Explanation

Sample Case 1: 
The binary representation of 5 is  101, so the maximum number of consecutive 1's is 1.

Sample Case 2: 
The binary representation of  13 is 1101 , so the maximum number of consecutive 1's is 2.

 

 1 #include <iostream>
 2 using namespace std;
 3 
 4 int main(){
 5     int n;
 6     cin >> n;
 7     int temp = n;
 8     int num = 0, max = 0;
 9     while(temp){
10         num = 0;
11         while(temp & 1){
12             num++;
13             temp >>= 1;
14         }
15         if(num > max)
16             max = num;
17         temp >>= 1;
18     }
19     cout << max << endl;
20     return 0;
21 }
View Code

 

 

 

转载于:https://www.cnblogs.com/qinduanyinghua/p/5531552.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值