Skip to content

Commit

Permalink
Solve 'Basics 08: Find next higher number with same Bits (1's)' kata
Browse files Browse the repository at this point in the history
  • Loading branch information
borisskert committed Jun 9, 2024
1 parent 2928807 commit 984e048
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 0 deletions.
24 changes: 24 additions & 0 deletions src/Kata.hs
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
13 changes: 13 additions & 0 deletions test/KataSpec.hs
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

0 comments on commit 984e048

Please sign in to comment.