Skip to content

Instantly share code, notes, and snippets.

@vikasverma787
Created April 30, 2018 11:17
Show Gist options
  • Save vikasverma787/2dcea0b8e751a9f066b8d895bff7d005 to your computer and use it in GitHub Desktop.
Save vikasverma787/2dcea0b8e751a9f066b8d895bff7d005 to your computer and use it in GitHub Desktop.
Bitwise operator
Count Bit Set
package com.algo.bits;
import java.io.*;
class countSetBits
{
/* Function to get no of set
bits in binary representation
of positive integer n */
static int countSetBits(int n)
{
int count = 0;
while (n > 0)
{
count += n & 1;
n >>= 1;
}
return count;
}
static int countSetBits(long n)
{
int count = 0;
while (n > 0)
{
count += n & 1;
n >>= 1;
}
return count;
}
// driver program
public static void main(String args[])
{
long i = 1000000099;
System.out.println(countSetBits(i));
}
}
-----------------------------------------------------------------
Find Duplicate in Array :
package com.algo.bits;
import java.util.ArrayList;
import java.util.List;
public class FindDuplicateInArray {
public static List<Integer> findDup(int[] arr) {
short status = 0;
List<Integer> l = new ArrayList<Integer>();
byte digit;
for (int temp = 0; temp < arr.length; temp++) {
digit = (byte) arr[temp];
if ((status & (1 << (digit))) > 0) {
l.add(arr[temp]);
// return false;
} else
status |= 1 << (digit);
}
return l;
}
static int countSetBits(int n) {
int count = 0;
while (n > 0) {
count += n & 1;
n >>= 1;
}
return count;
}
public void findNumber(int no) {
}
// Driver code
public static void main(String[] args) throws java.lang.Exception {
int[] arr = { 1, 5, 1, 10, 12, 10 };
for (int i : findDup(arr)) {
System.out.println(i);
}
}
}
------------------------------------------------------------------------------------
Find occurence once :
package com.algo.bits;
public class FindNumberWithOccurenceOne {
public static int xorApproach(int[] inputArray)
{
int result = 0;
for(int i=0;i<inputArray.length;i++)
{
result ^= inputArray[i];
}
return (result>0 ? result : -1);
}
public static void main(String[] args) {
int[] arr = { 1, 2, 2,1, 3,2 };
System.out.println(xorApproach(arr));
}
}
--------------------------------------------------------------------------------------
Unique Number :
package com.algo.bits;
class UniqueNumber{
public static boolean isUnique( int n ){
short status=0;
byte digit;
//System.out.println((2&4));
for( int temp=n; temp>0; temp/=10 ){
digit = (byte)(temp%10);
if( (status & (1<<(digit))) >0 ) return false;
else status |= 1<<(digit);
}
return true;
}
public static void main( String args[] ){
System.out.println(isUnique(343)); //1234 is a unique number
//System.out.println(isUnique(12342));//12342 is not a unique number
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment