30 Days of Code - Day 10: Binary Numbers

Objective

Today, we’re working with binary numbers. Check out the Tutorial tab for learning materials and an instructional video!

Task

Given a base-10 integer,n, convert it to binary (base-2). Then find and print the base-10 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 00

input00.txt
5
output00.txt
1

Explanation

The binary representation of 5 is 101, so the maximum number of consecutive 1’s is 1.

Sample 01

input01.txt
13
output01.txt
2

Explanation

The binary representation of 13 is 1101, so the maximum number of consecutive 1’s is 2.

Solution

main.go
package main

import "fmt"

func main() {
  var n, count, max int
  fmt.Scan(&n)

  for _, v := range fmt.Sprintf("%b", n) {
    if v == '1' {
      count++

      if count > max {
        max = count
      }
    } else {
      count = 0
    }
  }

  fmt.Println(max)
}