'Recursively count the number of bits required to represent a number
Hallo :) i wanna count the Binary numbers, with this Method
private static int helper ( int c,int zaehler){
if (c>>1 == 1){
return zaehler + 2;
}else{
return helper(c>>1,zaehler++);
}
Solution 1:[1]
So you want to recursively count the number of bits required to represent a number (i.e. log2)?
class Foo {
private static int helper (int c, int zaehler){
if (c == 0) {
// Base case, c = 0 so no more bits to count
return zaehler;
} else {
// c >>> 1 is the number without the LSB (assuming Java)
return helper(c >>> 1, zaehler + 1);
}
}
public static void main(String[] args) {
System.out.println(helper(Integer.parseInt(args[0]), 1));
}
}
Here are examples showing that it works:
$ java Foo 5 # 5 = 101
3
$ java Foo 15 # 15 = 1111
4
$ java Foo 16 # 16 = 10000
5
Solution 2:[2]
Given the clarification of what you want that you gave @thatotherguy, you can implement this without using zaehler and make it public without exposing yourself to the risk that somebody will make the initial call with an invalid second argument.
class TestNumBits {
public static int numBits(int c) {
if (c > 0) {
return 1 + numBits(c / 2);
}
if (c == 0) {
return 0;
}
return numBits(-c);
}
public static void main(String[] args) {
System.out.println(numBits(Integer.parseInt(args[0])));
}
}
Sample output:
$ java TestNumBits 3
2
$ java TestNumBits 5
3
$ java TestNumBits -5
3
$ java TestNumBits 10
4
$ java TestNumBits 16
5
Solution 3:[3]
You can use bitwise operators to get the answer. Here's an exmple on Python:
def countBits(n):
if n<=1:
return 1
else:
return 1+countBits(n>>1)
n = int(input("Enter a number greater than -1\n> "))
bits = countBits(n)
print(f"You need {bits} bit(s) to represent number {n} ({bin(n)})")
Note that this example works only with integers greater than -1
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | |
| Solution 3 |
