Skip to content

Commit

Permalink
Merge pull request #880 from vaskoz/day433
Browse files Browse the repository at this point in the history
Day433
  • Loading branch information
vaskoz committed Feb 2, 2020
2 parents 864b32a + 2f7564b commit c88d5fa
Show file tree
Hide file tree
Showing 3 changed files with 48 additions and 0 deletions.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -427,6 +427,7 @@ problems from
* [Day 427](https://github.com/vaskoz/dailycodingproblem-go/issues/861)
* [Day 428](https://github.com/vaskoz/dailycodingproblem-go/issues/864)
* [Day 429](https://github.com/vaskoz/dailycodingproblem-go/issues/866)
* [Day 433](https://github.com/vaskoz/dailycodingproblem-go/issues/879)
* [Day 434](https://github.com/vaskoz/dailycodingproblem-go/issues/870)
* [Day 435](https://github.com/vaskoz/dailycodingproblem-go/issues/868)
* [Day 436](https://github.com/vaskoz/dailycodingproblem-go/issues/877)
Expand Down
18 changes: 18 additions & 0 deletions day433/problem.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
package day433

// NextIntSameSetBits returns the next greater
// integer with the same set bits.
func NextIntSameSetBits(n int) int {
res := 0

if n != 0 {
rightMostBitInt := n & -n
nextHigherSetBitInt := n + rightMostBitInt
d := n ^ nextHigherSetBitInt
d /= rightMostBitInt
d >>= 2
res = nextHigherSetBitInt | d
}

return res
}
29 changes: 29 additions & 0 deletions day433/problem_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
package day433

import "testing"

// nolint
var testcases = []struct {
n, next int
}{
{6, 9},
{156, 163},
}

func TestNextIntSameSetBits(t *testing.T) {
t.Parallel()

for _, tc := range testcases {
if next := NextIntSameSetBits(tc.n); next != tc.next {
t.Errorf("Expected %v, got %v", tc.next, next)
}
}
}

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

0 comments on commit c88d5fa

Please sign in to comment.