-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Solve 'Basics 08: Find next higher number with same Bits (1's)' kata
- Loading branch information
1 parent
2928807
commit 984e048
Showing
2 changed files
with
37 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,24 @@ | ||
module Kata (nextHigher) where | ||
|
||
-- https://www.codewars.com/kata/56bdd0aec5dc03d7780010a5/train/haskell | ||
|
||
nextHigher :: Int -> Int | ||
nextHigher n = search (n + 1) | ||
where | ||
bitCountN = bitCount n | ||
|
||
search :: Int -> Int | ||
search i | ||
| bitCount i == bitCountN = i | ||
| otherwise = search (i + 1) | ||
|
||
bitCount :: Int -> Int | ||
bitCount 0 = 0 | ||
bitCount n | ||
| rest == 0 = bitCount div2 | ||
| otherwise = 1 + bitCount div2 | ||
where | ||
(div2, rest) = n `divMod` 2 | ||
|
||
-- #againwhatlearned | ||
-- use `popCount` from `Data.Bits` to count the number of bits set to 1 in a number |
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,13 @@ | ||
module KataSpec (spec) where | ||
|
||
import Kata (nextHigher) | ||
import Test.Hspec | ||
|
||
spec :: Spec | ||
spec = do | ||
it "basic tests" $ do | ||
nextHigher 128 `shouldBe` 256 | ||
nextHigher 1 `shouldBe` 2 | ||
nextHigher 1022 `shouldBe` 1279 | ||
nextHigher 127 `shouldBe` 191 | ||
nextHigher 1253343 `shouldBe` 1253359 |