How to calculate the number of zeros in binary? - java

Hi I am making a method that can take an integer as a parameter and compute how many zeros its binary form has. So for example, if I have binaryZeros(44), its binary form is 101100. Therefore, binaryZeros(44) should return 3. However, I am making some errors and I cannot tell where it is coming from. I would appreciate it if someone can point out where I am making that error, or if my approach (logic) to this problem is good enough. Thank you!
My code is Below:
public static int binaryZeros(int n) {
int zeroCount = 0;
double m = n;
while (m >= 0.0) {
m = m / 2.0;
if (m == Math.floor(m)) {
zeroCount++;
} else {
m = Math.floor(m);
}
}
return zeroCount;
}

Below is a more concise way to solve this problem
public static int binaryZeros(int n) {
int zeroCount = 0;
// Run a while loop until n is greater than or equals to 1
while(n >= 1)
{
/* Use modulo operator to get the reminder of division by 2 (reminder will be 1 or 0 as you are dividing by 2).
Keep in mind that binary representation is an array of these reminders until the number is equal to 1.
And once the number is equal to 1 the reminder is 1, so you can exit the loop there.*/
if(n % 2 == 0)
{
zeroCount++;
}
n = n / 2;
}
return zeroCount;
}

Your approach is good, but I think there's a better way to do it. The Integer class has a static method that returns the binary of a number: Integer.toBinaryString(num) . This will return a String.
Then, you can just check if there are any 0 in that string with method that has a for loop and evaluating with an if:
public int getZeros(String binaryString){
int zeros = 0;
for(int i=0; i < binaryString.length; i++)
if(binaryString.charAt[i].equals('0')
zeros++;
return zeros;
}
I believe this would be a simpler option and it doesn't have any errors.

Once m == 0.0, it will never change, so your while loop will never stop.

If you start with a number m >= 0, it can never become negative no matter how many times you divide it by 2 or use Math.floor. The loop should stop when m reaches 0, so change the condition to while (m > 0.0).
Note that you could do the same thing with built-in standard library methods. For example, there is a method that returns the number of leading zeros in a number, and a method that returns the number of bits set to 1. Using both you can compute the number of zeros that are not leading zeros:
static int binaryZeros(int n) {
return Integer.SIZE - Integer.numberOfLeadingZeros(n) - Integer.bitCount(n);
}

Here is one way. It simply complements the integer reversing 1's and 0's and then counts the 1 bits. You should not be using floating point math when doing this.
~ complements the bits
&1 masks the low order bit. Is either 1 or 0
>>> shifts right 1 bit including sign bit.
System.out.println(binaryZeros(44) + " (" +Integer.toBinaryString(44) +")");
System.out.println(binaryZeros(-44) + " ("Integer.toBinaryString(-44)+")");
public static int binaryZeros(int v) {
int count = 0;
while (v != 0) {
// count 1 bits
// of ~v
count += (~v)&1;
v >>>=1;
}
return count;
}
Prints
3 (101100)
4 (11111111111111111111111111010100)

Just be simple, whe there's Integer.bitCount(n) method:
public static int binaryZeros(int n) {
long val = n & 0xFFFFFFFFL;
int totalBits = (int)(Math.log(val) / Math.log(2) + 1);
int setBits = Long.bitCount(val);
return totalBits - setBits;
}

public static int getZeros(int num) {
String str= Integer.toBinaryString(num);
int count=0;
for(int i=0; i<str.length(); i++) {
if(str.charAt(i)=='0') count++;
}
return count;
}
The method toBinaryString() returns a string representation of the integer argument as an unsigned integer in base 2. It accepts an argument in Int data-type and returns the corresponding binary string.
Then the for loop counts the number of zeros in the String and returns it.

Related

Extracting a digit from a number ranging from 0 to 99999

I am working at a programm right now where I need to sort an array of numbers ranging from 0 to 99999. In order to do so, one part of the task is to extract the digits from every number of the array, and that can be accomplished by
i = number / digit.
For example, for the number 23456, I am supposed to start by extracting the number 2, which can be done by using
digit = 10000
and calculating
i = 23456 / 10000 = 2.
A recursive call is then supposed to look at the next digit, so in this case we want to get
i = 23456 / digit = 3
and so on. I know that there are certain methods for this, but how can this be done with using only primitves? I already tried to play around with modulo and dividing the digit, but it's not giving any desired result.
Basic Formula
The n-th digit of a non-negative, integral, decimal number can be extracted by the following formula:
digit = ((num % 10^n) / 10^(n-1))
where % represents modulo division, / represents integer division, and ^ represents exponentiation in this example. Note that for this formula, the number is indexed LSD->MSD starting from 1 (not 0).
This formula will also work for non-decimal numbers (e.g. base 16) by changing 10 to the desired base. It will also work for negative numbers provided that absolute value of the final digit is taken. Finally, it can even function to extract the integer digits (but not fractional digits) of a floating point number simply by truncating and casting the floating-point number to an integral number before passing it to this formula.
Recursive Algorithm
So, to recursively extract all of the digits of a number of a certain length in order MSD->LSD, you can use the following Java method:
static public void extractDigits(int num, int length) {
if (length <= 0) { // base case
return;
}
else { // recursive case
int digit = (num % (int)Math.pow(10,length)) / (int)Math.pow(10,length-1);
/* do something with digit here */
extractDigits(num, length-1); // recurse
}
}
This method will never divide by zero.
Note: In order to "do something with digit here," you may need to pass in an additional parameter (e.g. if you want to add the digit to a list).
Optimization
Since your goal is to extract every digit from a number, rather than only one specific digit (as the basic formula assumes), this algorithm may be optimized to extract digits in order LSD->MSD so as to avoid the need for exponentiation at each step. (this approach original given here by #AdityaK ...please upvote them if you use it)
static public void extractDigits(int num) {
if (num == 0) { // base case
return;
}
else { // recursive case
int digit = num % 10;
/* do something with digit here */
extractDigits(num / 10); // recurse
}
}
Note: Any negative number should be converted to a positive number before passing it to this method.
Here's the code to recursively extract numbers from an integer. It will be in reverse order.
import java.util.*;
public class HelloWorld{
static void extractNumbers(int n, List<Integer> l) {
if(n==0)
return;
else {
l.add(n%10);
extractNumbers(n/10, l);
}
}
public static void main(String []args){
List<Integer> result = new ArrayList<Integer>();
extractNumbers(456789,result);
System.out.println(result);
}
}
Hope it helps.
I would do something like this:-
public static void main (String[] args) throws java.lang.Exception
{
// your code goes here
int num=23456;
int numSize=5;
rec(num,numSize);
}
public static void rec(int num, int numSize){
if(numSize==0)
return;
int divideBy=(int)Math.pow(10,(numSize-1));
int out=(int)(num/divideBy);
System.out.println(out);
rec((num-out*divideBy),(numSize-1));
return;
}
See the output from here: http://ideone.com/GR3l5d
This can be easily done by using the for loop by converting the array elements into string.
var arr = [234, 3456, 1234, 45679, 100];
var compare = function(val1, val2) {
return val1 - val2;
};
arr.sort(compare); //sort function
var extract = function(value, index) {
var j = "";
var element = value + "";
for (var i in element) {
var val = element[i];
console.log(parseInt(val)); // this prints the single digits from each array elements
j = j + " " + val;
}
alert(j);
};
arr.forEach(extract); //extract function..

count Number of 1 Bits in java

I encountered a strange problem while doing an leetcode problem. This is about bits representation in Java.
Write a function that takes an unsigned integer and returns the number of ’1' bits it has (also known as the Hamming weight).
For example, the 32-bit integer ’11' has binary representation 00000000000000000000000000001011, so the function should return 3.
My solution is
public class Solution {
// you need to treat n as an unsigned value
public int hammingWeight(int n) {
int count = 0;
for(int i = 0; i < 32; ++i){
if((n >>> i) % 2 == 1){
++count;
}
}
return count;
}
}
This code is not accepted because of the input case:
4294967295 (11111111111111111111111111111111)
I reviewed the bit representation of integer in java but still do not know the problem of the solution?
Could anyone help me?
public int hammingWeight(int n) {
return Integer.bitCount(n);
}
Integer.bitCount(int i)
Returns the number of one-bits in the two's complement binary
representation of the specified int value.
The issue is performing modulo when you want a bitwise &. Something like,
public static int hammingWeight(int n) {
int count = 0;
for (int i = 0; i < 32; ++i) {
if (((n >>> i) & 1) == 1) {
++count;
}
}
return count;
}
public static void main(String[] args) {
int c = -1;
System.out.println(hammingWeight(c));
}
Outputs (as expected)
32
Java uses twos compliment. So the negative bit is the far left one. That means if you have a number greater than Integer.MAX_VALUE your input will be a negative number. When you do %2the sign remains unchanged. An alternative would be to use &1which will change the sign bit. After the first iteration, and you have done a bit shift, the sign bit will be zero.

Changing numbers places in java

Can anyone please learn me how to change this number 5486 to 4568 ? I need to change two pairs of numbers places. Any ideas please?
My code :
public Number shiftRight(int n) {
int length = (getNumOfDigits()+MINUSONE);
length = (int) Math.pow(TEN, length);
for (int i=0; i<n; i++){
int m=num%TEN;
num=(m*length) + (num/TEN);
}
return new Number(num);
}
public int shiftRightDistance(Number other){
int max = getNumOfDigits();
for (int i=0;i<max;i++)
{
if(compareTo(shiftRight(i))==ZERO)
{
return i;
}
}
return MINUSONE;
}
public Number swapPairs() {
}
}
The simplest (and least confusing) thing might be to convert the number to a char array, swap pairs of characters, and then convert back to a number. You can use String.valueOf(int), String.toCharArray(), new String(char[]) and Integer.valueOf(String) to put that together.
Alternatively, you can build on the following method that swaps the digits of a non-negative number less than 100:
private int swapDigitsLessThan100(int n) {
return 10 * (n % 10) + n / 10;
}
The way to build on that would be to extract every pair of digits from the original number, working recursively. The following deals with numbers that are an even number of digits long:
public int swapDigits(int n) {
if (n == 0) {
return 0;
return 100 * swapDigits(n / 100) + swapDigitsLessThan100(n % 100);
}
With this code, if n is an odd number of digits, the result will be to use a leading 0 as an additional digit.

Checksums - ISBN program

This problem has me puzzled. I tried using a loop like this: Basically I tried to get the first digit from the input and do the formula but it doesn't seem to work. It looks so simple but I can't figure it out. Could you help me? Thanks.
public static int ISBN(String ninedigitNum) {
number = 9;
while (number > 0) {
int nextDigit = ninedigitNum.substring(0,1);
...
}
Checksums (Source: Princeton University). The International Standard
Book Number (ISBN) is a 10 digit code that uniquely specifies a book.
The rightmost digit is a checksum digit which can be uniquely
determined from the other 9 digits from the condition that d1 + 2d2 +
3d3 + ... + 10d10 must be a multiple of 11 (here di denotes the ith
digit from the right). The checksum digit d1 can be any value from 0
to 10: the ISBN convention is to use the value X to denote 10.
Example: the checksum digit corresponding to 020131452 is 5 since is
the only value of d1 between 0 and and 10 for which d1 + 2*2 + 3*5 +
4*4 + 5*1 + 6*3 + 7*1 + 8*0 + 9*2 + 10*0 is a multiple of 11. Create a
Java method ISBN() that takes a 9-digit integer as input, computes the
checksum, and returns the 10-digit ISBN number. Create 3 JUnit test
cases to test your method.
I got it, thanks a lot everyone!
What about it isn't working? Either way, I believe what you're missing is that you're continually getting the same substring, which will be the first number of the string: int nextDigit = ninedigitNum.substring(0,1);. In addition, you're going to want to use an int, not a String; you can technically convert from String to int if desired, but the problem itself calls for an int.
There are two ways to do this that jump to mind. I would do this by realizing that mod in powers of 10 will give you the respective digit of an integer, but the easier way is to convert to a char array and then access directly. Note that there's no error checking here; you'll have to add that yourself. In addition, there are a LOT of 'magic numbers' here: good code typically has very, very few. I would recommend learning more data structures before attempting problems like these; to be honest there's very few things you can do without at least arrays and linked lists.
char[] ISBN = ninedigitNum.toCharArray();
//Process each number
int total = 0;
for(int i=0; i<9; i++){
int current_int = Integer.parseInt(ISBN[i]);
total += current_int * (10 - i)
}
//Find value of d1
for(int i=0; i<9; i++){
if(((total + i) % 11) == 0){
total += i*100000000;
break;
}
}
return total;
In general: Use print outs with System.out.println(x); or use your compiler's debugger to see what's going on during processing.
So,
This is the piece of code that I wrote. I still think it could be made more efficient.
public class Problem3 {
public static String ISBN(String x)
{
char[]temp = x.toCharArray();
int counter = 2;
int sum = 0;
int j=0;
for(int i=8;i>=0;i--)
{
sum+= counter*Integer.parseInt(""+temp[i]);
counter+=1;
}
for(j=0;j<10;j++)
{
if((sum+j)%11==0)
{
break;
}
}
return x+""+j;
}
public static void main(String args[])
{
String a = "020131452";
System.out.println(ISBN(a));
}
}
Hope this helps.
This works:
public static int ISBN(String nineDigitNum){
int sum = 0;
for(int i = 0; i<nineDigitNum.length(); i++){
sum += Integer.parseInt(""+nineDigitNum.charAt(i))*(10-i);
}
return (sum%11);
}
Also I believe if the checksum is == to 10, it should return an X, so you could either change the return type and add an if statement somewhere, or just put the if statement outside wherever you are using this method.
Here is a short one without loops that uses only substring(), charAt() and length():
public static String ISBN(String nineDigits) {
int chkD = 11 - checkDigit(nineDigits, 0);
return nineDigits + ((chkD == 10) ? "X" : chkD);
}
public static int checkDigit(String nDsub, int chkD) {
if (nDsub.length() == 0)
return 0;
chkD = ((nDsub.charAt(0) - '0') * (nDsub.length() + 1));
return (chkD + checkDigit(nDsub.substring(1), chkD)) % 11;
}
Output:
> ISBN("123456789")
"123456789X"
> ISBN("123456780")
"1234567806"

Number of zero bits in integer except leading zeros

If I have an integer in Java how do I count how many bits are zero except for leading zeros?
We know that integers in Java have 32 bits but counting the number of set bits in the number and then subtracting from 32 does not give me what I want because this will also include the leading zeros.
As an example, the number 5 has one zero bit because in binary it is 101.
Take a look at the API documentation of Integer:
32 - Integer.numberOfLeadingZeros(n) - Integer.bitCount(n)
To count non-leading zeros in Java you can use this algorithm:
public static int countNonleadingZeroBits(int i)
{
int result = 0;
while (i != 0)
{
if (i & 1 == 0)
{
result += 1;
}
i >>>= 1;
}
return result;
}
This algorithm will be reasonably fast if your inputs are typically small, but if your input is typically a larger number it may be faster to use a variation on one of the bit hack algorithms on this page.
Count the total number of "bits" in your number, and then subtract the number of ones from the total number of bits.
This what I would have done.
public static int countBitsSet(int num) {
int count = num & 1; // start with the first bit.
while((num >>>= 1) != 0) // shift the bits and check there are some left.
count += num & 1; // count the next bit if its there.
return count;
}
public static int countBitsNotSet(int num) {
return 32 - countBitsSet(num);
}
Using some built-in functions:
public static int zeroBits(int i)
{
if (i == 0) {
return 0;
}
else {
int highestBit = (int) (Math.log10(Integer.highestOneBit(i)) /
Math.log10(2)) + 1;
return highestBit - Integer.bitCount(i);
}
}
Since evaluation order in Java is defined, we can do this:
public static int countZero(int n) {
for (int i=1,t=0 ;; i<<=1) {
if (n==0) return t;
if (n==(n&=~i)) t++;
}
}
Note that this relies on the LHS of an equality being evaluated first; try the same thing in C or C++ and the compiler is free to make you look foolish by setting your printer on fire.

Categories

Resources