Skip to content

Commit

Permalink
day 214: convert to binary string and then count
Browse files Browse the repository at this point in the history
  • Loading branch information
vaskoz committed Mar 24, 2019
1 parent c24a905 commit 0ba066a
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 0 deletions.
25 changes: 25 additions & 0 deletions day214/problem.go
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
package day214

import "strconv"

// LengthLongestConsecutiveRunOnesBitShift calculates the longest
// run of 1's using bit shifting.
func LengthLongestConsecutiveRunOnesBitShift(n int) int {
Expand All @@ -15,5 +17,28 @@ func LengthLongestConsecutiveRunOnesBitShift(n int) int {
}
n >>= 1
}
if count > max {
return count
}
return max
}

// LengthLongestConsecutiveRunOnesString converts the number
// into a binary representation string.
func LengthLongestConsecutiveRunOnesString(n int) int {
var max, count int
for _, digit := range strconv.FormatInt(int64(n), 2) {
if digit == '1' {
count++
} else {
if count > max {
max = count
}
count = 0
}
}
if count > max {
return count
}
return max
}
19 changes: 19 additions & 0 deletions day214/problem_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@ var testcases = []struct {
longestConsecutiveOnes int
}{
{156, 3},
{20432348234, 3},
{65535, 16},
}

func TestLengthLongestConsecutiveRunOnesBitShift(t *testing.T) {
Expand All @@ -25,3 +27,20 @@ func BenchmarkLengthLongestConsecutiveRunOnesBitShift(b *testing.B) {
}
}
}

func TestLengthLongestConsecutiveRunOnesString(t *testing.T) {
t.Parallel()
for _, tc := range testcases {
if result := LengthLongestConsecutiveRunOnesString(tc.n); result != tc.longestConsecutiveOnes {
t.Errorf("Given n=%d, expected %d, got %d", tc.n, tc.longestConsecutiveOnes, result)
}
}
}

func BenchmarkLengthLongestConsecutiveRunOnesString(b *testing.B) {
for i := 0; i < b.N; i++ {
for _, tc := range testcases {
LengthLongestConsecutiveRunOnesString(tc.n)
}
}
}

0 comments on commit 0ba066a

Please sign in to comment.