Counting 1-s

Report a typo

You get a number as input. It will be the start of a range. All following numbers of the range are obtained by incrementing the previous number by one. You need to find three numbers (starting from the given one) that each contain five 1-s in the binary number notation and print them.

To get a binary number from decimal notation, we can use division by two. The first step is division with remainder. The remainder is equal to the digit of binary notation. The second step is integer division. We need it to get the next digit of binary notation. Repeat both steps until the result of the integer division is equal to zero. To get the correct notation, we need to reverse the resulting sequence.

Let's take a look at an example. We will try to convert 6 step by step using the code below:

num := 6

while num > 0 {
    digit := num % 2
    num /= 2
}

We can represent the code flow in a table:

num num > 0 digit
6 true 0
3 true 1
1 true 1
0 false -

From the number 6 we've got the sequence 0 1 1. What remains is to reverse the sequence, and we get the binary notation of the decimal 6: 610 = 1102.

In the current task, you don't need to use the last step (reversing), because to get the answer, you only need to know the count of units, not their order.

Sample Input 1:

15

Sample Output 1:

31
47
55
Write a program in Go
package main

import "fmt"

const FiveUnits = 5

func main() {
var numberRange, counter int
fmt.Scan(&numberRange)

MainLoop:
for counter < 3 {
number := numberRange
binCounter := 0

for number > 0 {
binCounter += number % 2
number /= 2

if ? > FiveUnits {
numberRange++
continue ?
}
}

if ? == FiveUnits {
fmt.Println(?)
counter++
}

numberRange++
}
}
___

Create a free account to access the full topic