Skip to content

Commit

Permalink
Merge 0ba066a into c7457bf
Browse files Browse the repository at this point in the history
  • Loading branch information
vaskoz committed Mar 24, 2019
2 parents c7457bf + 0ba066a commit 71602be
Show file tree
Hide file tree
Showing 3 changed files with 91 additions and 0 deletions.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -224,3 +224,4 @@ problems from
* [Day 211](https://github.com/vaskoz/dailycodingproblem-go/issues/434)
* [Day 212](https://github.com/vaskoz/dailycodingproblem-go/issues/436)
* [Day 213](https://github.com/vaskoz/dailycodingproblem-go/issues/439)
* [Day 214](https://github.com/vaskoz/dailycodingproblem-go/issues/441)
44 changes: 44 additions & 0 deletions day214/problem.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
package day214

import "strconv"

// LengthLongestConsecutiveRunOnesBitShift calculates the longest
// run of 1's using bit shifting.
func LengthLongestConsecutiveRunOnesBitShift(n int) int {
var max, count int
for n != 0 {
if n&1 == 1 {
count++
} else {
if count > max {
max = count
}
count = 0
}
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
}
46 changes: 46 additions & 0 deletions day214/problem_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
package day214

import "testing"

var testcases = []struct {
n int
longestConsecutiveOnes int
}{
{156, 3},
{20432348234, 3},
{65535, 16},
}

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

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

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 71602be

Please sign in to comment.