Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save MinSomai/8d77227f9e00f7aa52baba37be289e3c to your computer and use it in GitHub Desktop.
Save MinSomai/8d77227f9e00f7aa52baba37be289e3c to your computer and use it in GitHub Desktop.
Day 10 : Golang | Binary Numbers - Hackerrank.go
package main
import (
"bufio"
"fmt"
"io"
"os"
"strconv"
"strings"
)
func countConsecutiveOnes(binaryValue string) {
heighestCount := 0
tempHighestCount := 0
for index, char := range binaryValue {
stringChar := string(char)
if index == 0 && stringChar == "1" && tempHighestCount == 0 {
tempHighestCount = 1
}
if index > 0 && stringChar == "1" {
if stringChar == string(binaryValue[index-1]) {
if tempHighestCount == 0 {
tempHighestCount = 2
} else {
tempHighestCount++
}
if tempHighestCount > heighestCount {
heighestCount = tempHighestCount
}
} else {
if tempHighestCount > heighestCount {
heighestCount = tempHighestCount
} else {
tempHighestCount = 0
}
}
}
}
fmt.Println(heighestCount)
}
func main() {
reader := bufio.NewReaderSize(os.Stdin, 1024*1024)
nTemp, err := strconv.ParseInt(readLine(reader), 10, 64)
checkError(err)
n := int32(nTemp)
base2 := strconv.FormatInt(int64(n), 2)
countConsecutiveOnes(string(base2))
}
func readLine(reader *bufio.Reader) string {
str, _, err := reader.ReadLine()
if err == io.EOF {
return ""
}
return strings.TrimRight(string(str), "\r\n")
}
func checkError(err error) {
if err != nil {
panic(err)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment