-
Notifications
You must be signed in to change notification settings - Fork 32
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
day 161: reverse the bits of a 32-bit integer
- Loading branch information
Showing
2 changed files
with
44 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,17 @@ | ||
package day161 | ||
|
||
// Reverse32Bits reverses the bits and returned the result. | ||
// Runs in O(32) time. | ||
func Reverse32Bits(num uint32) uint32 { | ||
var rev uint32 | ||
offset := uint(32) | ||
for num != 0 { | ||
offset-- | ||
rev <<= 1 | ||
if num&1 == 1 { | ||
rev ^= 1 | ||
} | ||
num >>= 1 | ||
} | ||
return rev << offset | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,27 @@ | ||
package day161 | ||
|
||
import "testing" | ||
|
||
var testcases = []struct { | ||
given, expected uint32 | ||
}{ | ||
{4042322160, 252645135}, | ||
{3, 3221225472}, | ||
} | ||
|
||
func TestReverse32Bits(t *testing.T) { | ||
t.Parallel() | ||
for _, tc := range testcases { | ||
if result := Reverse32Bits(tc.given); result != tc.expected { | ||
t.Errorf("Expected %v got %v", tc.expected, result) | ||
} | ||
} | ||
} | ||
|
||
func BenchmarkReverse32Bits(b *testing.B) { | ||
for i := 0; i < b.N; i++ { | ||
for _, tc := range testcases { | ||
Reverse32Bits(tc.given) | ||
} | ||
} | ||
} |