diff --git a/kata/7-kyu/count-the-ones/README.md b/kata/7-kyu/count-the-ones/README.md new file mode 100644 index 00000000..f59d41ec --- /dev/null +++ b/kata/7-kyu/count-the-ones/README.md @@ -0,0 +1,12 @@ +# [Count the Ones](https://www.codewars.com/kata/count-the-ones "https://www.codewars.com/kata/5519e930cd82ff8a9a000216") + +The __Hamming weight__ of a string is the number of symbols that are different from the zero-symbol of the alphabet used. There are several +algorithms for efficient computing of the Hamming weight for numbers. In this Kata, speaking technically, you have to find out the number +of '1' bits in a binary representation of a number. Thus, + +``` +hammingWeight(10) // 1010 => 2 +hammingWeight(21) // 10101 => 3 +``` + +The interesting part of this task is that you have to do it *without* string operation (hey, it's not really interesting otherwise) \ No newline at end of file diff --git a/kata/7-kyu/count-the-ones/main/HammingWeight.java b/kata/7-kyu/count-the-ones/main/HammingWeight.java new file mode 100644 index 00000000..36358840 --- /dev/null +++ b/kata/7-kyu/count-the-ones/main/HammingWeight.java @@ -0,0 +1,5 @@ +interface HammingWeight { + static int hammingWeight(int i) { + return Integer.bitCount(i); + } +} \ No newline at end of file diff --git a/kata/7-kyu/count-the-ones/test/SolutionTest.java b/kata/7-kyu/count-the-ones/test/SolutionTest.java new file mode 100644 index 00000000..86a09dc2 --- /dev/null +++ b/kata/7-kyu/count-the-ones/test/SolutionTest.java @@ -0,0 +1,15 @@ +import static org.junit.jupiter.api.Assertions.assertEquals; + +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; + +class SolutionTest { + @ParameterizedTest + @CsvSource(textBlock = """ + 10, 2 + 21, 3 + """) + void sample(int n, int expected) { + assertEquals(expected, HammingWeight.hammingWeight(n)); + } +} \ No newline at end of file diff --git a/kata/7-kyu/index.md b/kata/7-kyu/index.md index 2f559797..e50a6af5 100644 --- a/kata/7-kyu/index.md +++ b/kata/7-kyu/index.md @@ -119,6 +119,7 @@ - [Count consonants](count-consonants "564e7fc20f0b53eb02000106") - [Count the Digit](count-the-digit "566fc12495810954b1000030") - [Count the divisors of a number](count-the-divisors-of-a-number "542c0f198e077084c0000c2e") +- [Count the Ones](count-the-ones "5519e930cd82ff8a9a000216") - [Covfefe](covfefe "592fd8f752ee71ac7e00008a") - [Create palindrome](create-palindrome "5b7bd90ef643c4df7400015d") - [Credit card issuer checking](credit-card-issuer-checking "5701e43f86306a615c001868")