Tuesday, July 12, 2016

Hacker Rank 30 days of code Day 10: Binary Numbers

The problem

Objective 
Today, we're working with binary numbers. Check out the Tutorial tab for learning materials and an instructional video!
Task 
Given a base- integer, , convert it to binary (base-). Then find and print the base- integer denoting the maximum number of consecutive 's in 's binary representation.
Input Format
A single integer, .
Constraints
Output Format
Print a single base- integer denoting the maximum number of consecutive 's in the binary representation of .
Sample Input 1
5
Sample Output 1
1
Sample Input 2
13
Sample Output 2
2
Explanation
Sample Case 1: 
The binary representation of  is , so the maximum number of consecutive 's is .
Sample Case 2: 
The binary representation of  is , so the maximum number of consecutive 's is .

My submission
 #include <map>  
 #include <set>  
 #include <list>  
 #include <cmath>  
 #include <ctime>  
 #include <deque>  
 #include <queue>  
 #include <stack>  
 #include <string>  
 #include <bitset>  
 #include <cstdio>  
 #include <limits>  
 #include <vector>  
 #include <climits>  
 #include <cstring>  
 #include <cstdlib>  
 #include <fstream>  
 #include <numeric>  
 #include <sstream>  
 #include <iostream>  
 #include <algorithm>  
 #include <unordered_map>  
 using namespace std;  
 int main(){  
      int n;  
      cin >> n;  
      int maxConsecutive, currentConsecutive = 0;  
      while (n > 0) {  
           if (n % 2 == 1){  
                currentConsecutive++;  
                if (currentConsecutive > maxConsecutive)  
                     maxConsecutive = currentConsecutive;  
           } else {  
                currentConsecutive = 0;  
           }  
           n /= 2;  
      }  
      cout << maxConsecutive;  
 }  

2 comments:

  1. public class Solution {

    public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
    int n = in.nextInt();
    int count = 0;
    int consecutiveone = 0;
    while(n > 0) {
    if(n % 2 == 0) {
    count = 0;
    }
    if(n%2 == 1) {
    count++;
    if(count >= consecutiveone) {
    consecutiveone = count;
    }
    }
    n= n/2;
    }
    System.out.println(consecutiveone);
    in.close();
    }
    }

    ReplyDelete
  2. In the world of www, there are countless blogs. But believe me, this blog has all the perfection that makes it unique in all. I will be back again and again. Hire a computer hacker

    ReplyDelete