Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

solved problem12 #109

Merged
merged 1 commit into from
Sep 30, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions javaProblems/problem12/Solution.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
public class Solution {
public int solve(int n) {
String string = Integer.toBinaryString(n);
int count = 0;
for (char digit : string.toCharArray()) {
if (digit == '1') {
count++;
}
}
return count;
}
}
27 changes: 27 additions & 0 deletions javaProblems/problem12/Test.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import java.util.logging.Level;
import java.util.logging.Logger;

public class Test {
public static void main(String[] args) {
Logger logger = Logger.getLogger(Logger.GLOBAL_LOGGER_NAME);
Solution solution = new Solution();

// Test case 1
int n = 00000000000000000000000000001011;
int ans1 = solution.solve(n);
if (ans1 != 3) {
logger.log(Level.SEVERE, "Test Case 1: Wrong solution!");
System.exit(1);
}

// Test case 2
int n2 = 00000000000000000000000010000000;
int ans2 = solution.solve(n2);
if (ans2 != 1) {
logger.log(Level.SEVERE, "Test Case 2: Wrong solution!");
System.exit(1);
}

System.out.print("All Testcases passed!");
}
}
18 changes: 18 additions & 0 deletions javaProblems/problem12/readme.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
# Number of 1 Bits

## Problem Statement
Write a function that takes the `binary representation` of an unsigned integer and returns the number of `'1'` bits it has (also known as the `Hamming weight`).

```
# Example 1

Input: n = 00000000000000000000000000001011
Output: 3


# Example 2

Input: n = 00000000000000000000000010000000
Output: 1

```