AdSense

Showing posts with label Bit manipulation. Show all posts
Showing posts with label Bit manipulation. Show all posts

Friday, April 3, 2015

Generate all sequences of n bits with all k unique bits

The problem came from Cracking the code interview:
Consider sequences of 36 bits. Each such sequence has 32 5 - bit sequences consisting of adjacent bits. For example, the sequence 1101011… contains the 5 - bit sequences 11010,10101,01011,…. Write a program that prints all 36 - bit sequences with the two properties: 
1. The first 5 bits of the sequence are 00000. 
2. No two 5 - bit subsequences are the same.

I generalized it to print all sequence of n  (n <= 64) bits with: 1. the first k bits of the sequence are 0s and 2. no two k - bit subsequences are the same.

There probably are smarter ways. I used the brutal force search. Start from kth bit, get all permutations of the sequence with the first k bits zero, then for every sequence, check if all bits are unique, and print out those that contain unique k - bit sequence and haven't been printed.

I am looking for a better approach, here is my open question of the problem on Stackoverflow.


import java.util.*;
public class UniquekBitSequence {

 public static void uniqueSequence(int n, int k){
  long rst = 0;
  uniqueSequence(n, k, rst, k - 1, new HashSet ());
 }
 private static void uniqueSequence(int n, int k, long rst, int start, Set printed){
  if(isDistinct(rst, n, k) && printed.add(rst)){
   System.out.println(Long.toBinaryString(rst));
  }
  for(int i = start + 1; i < n; i++){
   rst |= (1 << i);
   uniqueSequence(n, k, rst, i, printed);
   rst = setZero(rst, i);
   uniqueSequence(n, k, rst,  i, printed);
  }
 }
 public static int getInt(long rst, int right, int left){
  int mask = (1 << (left + 1)) - 1 - ((1 << (right)) - 1);
  return ((int)rst & mask) >> right;
 }
 public static long setZero(long rst, int start){
  int mask = ~(1 << start);
  return rst & mask;
 }
 private static boolean isDistinct(long rst, int n, int k){
  Set bits = new HashSet ();
  for(int i = k - 1; i < n; i++){
   if(!bits.add(getInt(rst, i - k + 1, i)))
    return false;
  }
  return true;
 }
 public static void main(String[] args){
  uniqueSequence(10, 5);
 }
}

Sunday, March 29, 2015

Integer to String


Write a function that takes an integer as input and produces an output string.
Some sample Input/outputs are as follows
i/p o/p
1 - A
2 - B
3 - AA
4 - AB
5 - BA
6 - BB
7 - AAA
8 - AAB
9 - ABA
10 - ABB
11 - BAA
12 - BAB
13 - BBA
14 - BBB
15 - AAAA

This looks like an integer to binary conversion, however, instead of using 0, 1 representation, it would be easier to understand if we convert in this way:

A       1
B       2
AA    11
AB    12
BA    21


If we use binary representations, we will have:

A       1
B       10
AA    11
AB    110
BA    101

It is reasonable that when n % 2 = 1, we append "A". However, if n % 2 = 0, we will have one extra digit, so we need to subtract 1 before we divide by 2.




public class IntegerToString {
 public static String convert(int n){
  if(n <= 0)
   return null;
  String rst = "";
  while(n > 0){
   if((n & 1) != 0)
    rst = "A" + rst;
   else {
    rst = "B" + rst;
    n -= 1;
   }
   n = (n >> 1);
  }
  return rst;
 }
 public static void main(String[] args) {
  for(int i = 1; i <= 15; i++)
   System.out.println(convert(i));
 }
}

Tuesday, March 24, 2015

Given an input file with four billion integers, provide an algorithm to generate an integer which is not contained in the file.Assume you have 1 GB of memory.
FOLLOW UPWhat if you have only 10 MB of memory?

This is a very interesting problem. The problem requires knowledge on both memory limits or bit operations, and consider I am not good at either, it becomes even more interesting.

So the first question, we have 1 GB memory
1GB memory is 2^30 bits, so if we use each bit to represent a number, we can put at most 2 ^ 30 numbers, which can fit 4 billion numbers. So the way we do it is to create a byte array with each element represent 1 byte, which can hold 8 numbers. We go through all the numbers and set the corresponding bit to 1. For example, 11 would be in the 2nd byte and the 3rd bit. Then we go through the byte array again, if a bit is not set to one, then that one is the missing one we are looking for.

public static void findMissing() throws FileNotFoundException{
  byte[] bitField = new byte[0xfffffff / 8];
  Scanner in = new Scanner(new FileReader("numbers"));
  while(in.hasNextInt()){
   int n = in.nextInt();
   bitField[n / 8] |= 1 << (n % 8);
  }
  boolean found = false;
  for(int i = 0; i < bitField.length && !found; i++){
   for(int j = 0; j < 8; j++){
    if((bitField[i] & (1 << j)) == 0){
     System.out.println(i * 8 + j);
     found = true;
     break;
    }
   }
  }
 }


Second, we have 10 MB memory
10 MB is around 2^23 + 2 bits, so we cannot put all numbers this time. Naturally we will think of separate the number so that we can fit each portion into the memory. So consider we have a bucket that can put 2^20 numbers, for 2^32 numbers, we will need 2^12 buckets (These numbers are from the solution provided by the book, I don't think the numbers are accurate here, but the idea is the same.  4 billion integers is around 2^30, so I think we only need 2 ^ 10 buckets, anyway).
We use two arrays, the bucket, which has the length of numBucket, and the bitField as the previous question. Now we go through all the numbers, if the number should be in the range of that bucket, we increase the count of that bucket. So if there is a bucket that has less numbers than it is supposed to have (2^20), we know there is at least one missing number in that bucket.
Now we go through the numbers again, and put all numbers in that range into the bitField, as we did in the last problem, and then we find the missing one.


public static void findMissing2() throws FileNotFoundException{
  int bitSize = 1048576; //2^20, number of numbers we need to put in one bucket
  int numBucket = 4096; // (2^32 / 2^20), number of buckets we need
  byte[] bitField = new byte[bitSize / 8];
  int[] blocks = new int[numBucket];
  Scanner in = new Scanner(new FileReader("numbers"));
  //count how many numbers are in each bucket
  while(in.hasNextInt()){
   int n = in.nextInt();
   blocks[n / bitSize]++;
  }
  int startNumber = 0;
  for(int i = 0; i < numBucket; i++){
   if(blocks[i] < bitSize){
    startNumber = i * bitSize;
    break;
   }
  }
  in = new Scanner(new FileReader("numbers"));
  while(in.hasNextInt()){
   int n = in.nextInt();
   if(n >= startNumber && n < startNumber + bitSize){
    bitField[(n - startNumber) / 8] |= (1 << (n - startNumber) % 8);
   }
  }
  boolean found = false;
  for(int i = 0; i < bitField.length && ! found; i++){
   for(int j = 0; j < 8; j++){
    if(((bitField[i] << j) & 1) == 0){
     System.out.println(startNumber + i * 8 + j);
     found = true;
     break;
    }
   }
  }
 }


Monday, March 9, 2015

Hamming weights

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.
Well, all I can say is, see Wikipedia.


public class Solution {
    // you need to treat n as an unsigned value
    public int hammingWeight(int i) {
        i = i - ((i >> 1) & 0x55555555);
        i = (i & 0x33333333) + ((i >> 2) & 0x33333333);
        return (((i + (i >> 4)) & 0x0F0F0F0F) * 0x01010101) >> 24;
    }
}

I do have an easier approach, apparently LeetCode doesn't accept it.


public int hammingWeight(int n) {
        int ones = 0;
        while(n > 0){
            if((n & 1) > 0)
                ones++;
            n = (n >> 1);
        }
        return ones;
    }

Reverse bits

Reverse bits of a given 32 bits unsigned integer.
For example, given input 43261596 (represented in binary as 00000010100101000001111010011100), return 964176192 (represented in binary as00111001011110000010100101000000).


I am still not good at bits operation. Even though now I can solve the problem by myself, it still takes certain time manner.


public class Solution {
    // you need treat n as an unsigned value
    public int reverseBits(int n) {
        if(n == 0)
            return n;
        int rst = 0;
        for (int b = 31; b >= 0; b--){
            rst |= ((n & 1) << b);
            n = n >> 1;
        }
        return rst;
    }
}

Sunday, March 1, 2015

Addition without any operators


Write a function that adds two numbers.You should not use + or any arithmetic operators.

Well, if we cannot use any operators, the only approach left is bit manipulation. 

Consider normally how we would add numbers. There are two parts, first addition, then carry. If we add numbers without carry, then 123 + 987 is 000. If only consider carry, then 123 + 987 is 1110. So in the end if we add two results together, we will have 123 + 987 = 1110 + 000 = 1110. 

Now the next thing, how we can do it with bits. The addition part, bit[i] will be 0 if both bits[i] in a and b is 0 or 1, yup, XOR. The carry part, bit[i] will be 1 if both bits[i - 1] in a and b is 1. It's AND, with 1 position left shift. 


public static int addition(int a, int b){
  if (b == 0)
   return a;
  int sum = a ^ b;
  int carry = (a & b) << 1;
  return addition(sum, carry);
 }

Compare two numbers

Write a method which finds the maximum of two numbers.You should not use if-else or any other comparison operator.
EXAMPLE
Input: 5, 10
Output: 10 

This is such an easy problem except you cannot use anything you can think of.
Let c = a - b, then the larger number between a and b = a + k * c where k = 0 if a is the larger one and k = 1 if b is the larger one. Now we need some help from the bits. If a number is negative, we know the 32nd bit of the number is 1, otherwise, it is 0. So the problem becomes find the most significant bit k of c = a - b and return max = a + k*c.


public static int getMax(int a, int b){
  int c = a - b;
  //the 32nd bit is 1 if the number is negative, 0 if positive
  int k = (c >> 31) & 1;
  int max = a - k * c;
  return max;
 }

Saturday, February 28, 2015

Swap numbers without temporary variables


Write a function to swap a number in place without temporary variables.
using XOR.  a = 3 (11), b = 5 (101). a = a ^ b = 110 b = a ^ b  =  3(11), because we flip the bits back. a = a ^ b = 5 (101)


public static void swap(int a, int b){
  a = a ^ b;
  b = a ^ b;
  a = a ^ b;
  System.out.println("a: " + a);
  System.out.println("b: " + b);
 }

Saturday, February 21, 2015

Assign numbers

There are numbers in between 0-9999999999 (10-digits) which are assigned to someone.
Write two methods called "getNumber" and "requestNumber" as follows: 
Number getNumber();
boolean requestNumber(Number number);
getNumber method should find out a number that did not assigned than marks it as assigned and return that number.
requestNumber method checks the number is assigened or not. If it is assigened returns false, else marks it as assigned and return true.
Design a data structure to keep those numbers and implement those methods

I like this problem a lot because it tests you two things: how to handle large data that may not fit into memory and how to use bits. I am good at neither. :(

Well, first, memory. So we have 10^10 numbers, each number takes 4 byte, so in total we will have ...eh... 40 GB data (thank you, Google!). It definitely cannot fit into the memory, so how should we deal with it? Remember 4 byte = 32 bits, so 1 integer takes 32 bits, can we only use 1 bit? That can reduce the memory to 40 / 32 ~ 1.25 GB, if we have a machine with 2 GB memory, we can handle it!

Yup, here comes the second, the BitSet. I wasn't quite familiar with the concept. A bit set is a vector of bits that grows as needed.  Each component of the bit set has a boolean value. So consider if I initialize a BitSet with initial size of 32, by flipping each component in the set (true -> false or false -> true), we can get 2^32 numbers, and that fits our problem set.

For the requestNumber() part, I use a hashSet to store all added numbers, this will allow retrieval of the number takes only O(1) time.


/**
 * 
 *There are numbers in between 0-9999999999 (10-digits) which are 
 *assigned to someone (does not matter which number assigned to whom) 
 *Write two methods called "getNumber" and "requestNumber" as follows 
 *
 *Number getNumber(); 
 *boolean requestNumber(Number number); 
 *
 *getNumber method should find out a number that 
 *did not assigned than marks it as assigned and return that number. 
 *requestNumber method checks the number is assigned or not. 
 *If it is assigned returns false, else marks it 
 *as assigned and return true. 
 *design a data structure to keep those numbers and implement those methods
 * @author shirleyyoung
 *
 */
import java.util.*;
public class AssignNumbers {
 private static BitSet bits = new BitSet(32);
 private static Set numbers = new HashSet ();
 private static void toBitSet(int number) {
  int index = 0;
  while (number != 0) {
   if (number % 2 != 0)
    bits.set(index);
   index++;
   // >> signed
   // >>> unsigned
   number = number >> 1;
  }
 }
 
 private static int toInteger() {
  int value = 0;
  for (int i = 0; i < bits.length();i++) {
   value += bits.get(i) ? (1 << i) : 0;
  }
  return value;
 }
 
 public static int getNumber() {
  if (!numbers.contains(toInteger())) {
   numbers.add(toInteger());
   return toInteger();
  }
  else {
   for (int i = 0; i < 32; i++) {
    bits.flip(i);
    if (!numbers.contains(toInteger())) {
     numbers.add(toInteger());
     return toInteger();
    }
   }
  }
  return -1;
 }
 public static boolean requestNumber(int number) {
  if (numbers.contains(number))
   return false;
  else {
   numbers.add(number);
   toBitSet(number);
   return true;
  }
 }

 public static void main(String[] args) {
  System.out.println(getNumber());
  //System.out.println(requestNumber(123));
  //System.out.println(requestNumber(123));
  //System.out.println(getNumber());
  for (int i = 0; i < 1000; i++) {
   System.out.println(getNumber());
  }

 }
}

Saturday, January 17, 2015

Number of ones in the binary representation of a number


Write a function that takes in an integer and returns the number of ones set in the binary representation.
This problem looks very easy. The way we do it is to compare the number  with 1 and left shift the number until it reaches zero.
Yeah...
But what about negative number? It is always less than zero.

The trick is, every negative number XOR with -1 will gives its positive counterpart less one (LO). For example, -123 ^ -1 = 122, -1 ^ -1 = 0. Since -1 has 32 ones, so the number of ones in any negative number is the number of zeros in LO. For example, the number of ones in -123 is the number of zeros in 122. So we only need to convert the negative number into its LO, then we can use the old method for positive integers.


public static int countOnes(int n) {
  if (n == 0)
   return 0;
  if (n == -1)
   return 32;
  int count = 0;
  boolean isNegative = false;
  if (n < 0) {
   isNegative = true;
   n = (-n) - 1;
  }
  while (n > 0) {
   if ((n & 1) == 1)
    count++;
   n = n >> 1;
  }
  return isNegative? 32 - count : count;
 }

Thursday, January 1, 2015

Find missing integer -- Bit manipulation


An array A[1...n] contains all the integers from 0 to n except for one number which is missing.In this problem, we cannot access an entire integer in A with a single operation.The elements of A are represented in binary, and the only operation we can use to access them is “fetch the jth bit of A[i]”, which takes constant time.Write code to find the missing integer.Can you do it in O(n) time?

I am not good at bit manipulation, and that's the reason every such problem becomes so interesting to me. This one, we need to implement a method for the very easy question: search a missing integer in an array. And no, no array traversal, only bit operation is allowed.

So, considering any array of integers that are in binary representations, what will it look like? 0s and 1s, right? Then, what will the least significant digit of numbers look like?

For any array, it will be like:

0 1 0 1 0 1

or

0 1 0 1 0 1 0

depending on if n is an odd number or even number. So from the above array, we can make a conclusion that the number of 0s in the array is always >= the number of 1s in the array.

Next, what will happen if an odd number is removed? The number of 1s will be strictly smaller than the number of 0s. And alternatively, if we remove an even number, the number of 1s will be >= the number of 0s.

Ok, now all we need to do is to separate the lists to 0s and 1s and check which one has the larger size.
If we have determined that 1 (0) is removed, we pretty much can get rid of half of the list. If 1 is removed, it definitely is an odd number so we only have to check the odd number list and alternatively if 0 is removed, we only need to look at the even number list.

The problem is almost solved. What's next? We move to the next digit! Yup, recursion.

So, what about complexity? Is it O(n)?

Well, let's see, at the beginning of the recursion, i.e., when we check the least significant digit, we go through the whole array, so it takes O(n) time. Then the next recursion, O(n/2) time since we only check half of the input array, and then.... yeah, you get it?

O(n) + O(n/2) + O(n/4) + ... =O(2n) = O(n).

A-ha!, it is O(n)!


public class BitInteger {
 public static final int INTEGER_SIZE = 32;
 private boolean[] bits;
 public BitInteger() {
  bits = new boolean[INTEGER_SIZE];
 }
 public BitInteger(int value) {
  bits = new boolean[INTEGER_SIZE];
  for (int j = 0; j < INTEGER_SIZE; j++) {
   if (((value >> j) & 1) == 1)
    bits[INTEGER_SIZE - 1 - j] = true;  
  }
 }
 public int fetch(int k) {
  if (bits[k])
   return 1;
  else
   return 0;
 }
 public void set (int k, int bitValue) {
  if (bitValue == 0)
   bits[k] = false;
  else
   bits[k] = true;
 }
 public void set (int k, char bitValue) {
  if (bitValue == '0')
   bits[k] = false;
  else
   bits[k] = true;
 }
 public void set(int k, boolean bitValue) {
  bits[k] = bitValue;
 }
 public void swapValues(BitInteger number) {
  for (int i = 0; i < INTEGER_SIZE; i++) {
   int tmp = number.fetch(i);
   number.set(i, this.fetch(i));
   this.set(i, tmp);
  }
 }
 public int toInt() {
  int number = 0;
  for (int j = INTEGER_SIZE - 1; j >= 0; j--) {
   number = number | fetch(j);
   if (j > 0)
    number = number << 1;
  }
  return number;
 }

}
public class FindMissing {
 public int findMissing(ArrayList input) {
  return theMissingNumber(input, BitInteger.INTEGER_SIZE - 1);
 }
 private int theMissingNumber(ArrayList input, int column) {
  if (column < 0)
   return 0;
  ArrayList oddIndices = new ArrayList ();
  ArrayList evenIndices = new ArrayList ();
  for (int i = 0; i < input.size(); i++) {
   if (input.get(i).fetch(column) == 0) 
    evenIndices.add(input.get(i));
   if (input.get(i).fetch(column) == 1)
    oddIndices.add(input.get(i));
  }
  if (evenIndices.size() > oddIndices.size()) 
   return (theMissingNumber(oddIndices, column - 1) << 1) | 1;
  else
   return (theMissingNumber(evenIndices, column - 1) << 1) | 0;
 }

}

Tuesday, December 30, 2014

All about bit manipulation


Check if a string has all unique characters


public boolean isUnique(String s) {
  if (s == null)
   throw new NullPointerException("Null string!");
  if (s.length() == 0)
   return true;
  int check = 0;
  for (int i = 0; i < s.length(); i++) {
   int val = Character.getNumericValue(s.charAt(i));
   if ((check & (1 << val)) > 0) 
    return false;
   check |= (1 << val);
  }
  return true;
 }

Insert bits

You are given two 32-bit numbers, N and M, and two bit positions, i and j.Write a method to set all bits between i and j in N equal to M (e.g., M becomes a substring of N located at i and starting at j).

Set all positions after j to zero
Set all positions after i back to 1
get the mask where all bits between i to j is cleared
put m into n from ith position

public int insertBitnumber(int m, int n, int posi, int posj) {
  //32 bit of 1s == -1;
  int max = ~0;
  /* e.g., posj = 3
   * 1 << posj = 1000
   * (1 << posj) - 1 = 111
   * max - that will leave all bits after j = 0;
   */
  int left = max - ((1 << posj) - 1);
  int right = (1 << posi) - 1;
  //this operation will leave all positions between posi and posj equals zero
  int mask = left | right;
  //mask & n will clear all bits between i and j in n
  // then we put m in those positions
  return (mask & n) | (m << posi);
  
 }


Decimal To Binary

Given a (decimal - e.g.3.72) number that is passed in as a string, print the binary representation.If the number can not be represented accurately in binary, print “ERROR” . 

Given an binary integer, we know that 1001 = 1 * 2^ 3 + 0 * 2 ^ 2 + 0 * 2 ^ 1 + 1 * 2^0 = 9. So if we keep doing mod operation and divide the number by 2, we can get the binary representation of the integer.
Analogously, 0.101 = 1 * (1/2)^1 + 0 * (1/2)^2 + 1 * (1/2)^3 = 0.625. Thus if we multiply the number by 2, we get 1 * (1/2)^0 + 0 * (1/2)^1 + 1 * (1/2)^2 = 1.25(10)  = 1.01(2). So if the result is greater than 1, we know that there should be 1 follows "." in the decimal part. We can do the same operation for every digit.


public class DecimalToBinary {
 public String decimalToBinary (String s) {
  if (s == null) 
   throw new NullPointerException("Null string");
  int intPart = Integer.parseInt(s.substring(0, s.indexOf('.')));
  double deciPart = Double.parseDouble(s.substring(s.indexOf('.')));
  
  String rst = "";
  while (intPart > 0) {
   rst = String.valueOf(intPart % 2) + rst;
   intPart >>= 1;
  }
  rst += ".";
  String decim = "";
  while (deciPart > 0) {
   if (decim.length() > 32) {
    return "Error";
   }
   if (deciPart == 1) {
    decim += "1";
    break;
   }
   double d = deciPart * 2;
   if (d >= 1) {
    decim += "1";
    deciPart = d - 1;
   }
   else {
    decim += "0";
    deciPart = d;
   }
  }
  return rst + decim;
 }

}

Next Largest and Smallest number that has the same number of 1 bits

Given an integer, print the next smallest and next largest number that have the same number of 1 bits in their binary representation.

Ok, this is interesting. So basically, given a binary number, 11100110, if we want to find the next largest one that has the same number of 1 bits, we first switch the first 0 to 1, which gives us 11101110, then we switch the next 1 after that 0 to 0, and results in 11101010. Since we want the next largest, we would want to  shift all the 1s after that to the most right side, and the result is: 11101001, yep, here is the solution.

The next smallest number is similar. Reversely, we switch the first 1 to 0 and the next 0 to 1. Using another example 110011 would result in 101011, and shifts, and the answer is: 101110.


public class NextBitNumber {
 private int setBit(int n, int index, boolean toOne) {
  int rst;
  if (toOne)
   rst = n | (1 << index);
  else {
   int mask = ~ (1 << index);
   rst = n & mask;
  }
  return rst;
 }
 private boolean getBit(int n, int index) {
  return (n & (1 << index)) > 0;
 }
 public int nextLargest(int n) {
  if (n <= 0)
   return -1;
  int index = 0;
  int countOnes = 0;
  while (!getBit(n, index))
   index++;
  while(getBit(n, index)) {
   index++;
   countOnes++;
  }
  n = setBit(n, index, true);
  index--;
  n = setBit(n, index, false);
  countOnes--;
  index--;
  for (int i = index; i > index - countOnes; i--) 
   n = setBit(n, i, false);
  for (int i = 0; i < countOnes; i++)
   n = setBit(n, i, true);
  return n;
 }
 public int nextSmallest(int n) {
  if (n <= 0)
   return -1;
  int index = 0;
  int countZeros = 0;
  while (getBit(n, index)) {
   index++;
  }
  while (!getBit(n, index)) {
   index++;
   countZeros++;
  }
  n = setBit(n, index, false);
  index--;
  n = setBit(n, index, true);
  index--;
  countZeros--;
  for (int i = index; i > index - countZeros; i--)
   n = setBit(n, i, true);
  for (int i = 0; i < countZeros; i++)
   n = setBit(n, i, false);
  return n;
 }

}

What does (n & (n - 1)) == 0 used for? 

Check if n == 0 or power of 2!
For example, 100 and 11;

Bits needed to convert a number to another number

Write a function to determine the number of bits required to convert integer A to integer B.
Input: 31, 14
Output: 2 

Count the number of different bits in a number by using XOR.


public class BitsNeededToConvert {
 public int bitsNeeded(int a, int b) {
  if (a == b)
   return 0;
  int count = 0;
  for (int c = a ^ b; c >= 0; c = c>> 1) {
   count += c & 1;
  }
  return count;
 }

}


Something about Hexadecimal

In Unix shells, and C programming language:
prefix 0x for numeric constants represented in hex. e.g., 0x5A3 (144310).
Character and string constants may express characters codes in hexadecimal with the prefix \x followed by two hex digits: \x1B (Esc control character)
Unicode standard:
A character value is represented with U+ followed by the hex value, e.g., U+20AC (euro sign)

Convert hexadecimal to binary

Swap odd and even bits in a number

Write a program to swap odd and even bits in an integer with as few instructions as possible (e.g., bit 0 and bit 1 are swapped, bit 2 and bit 3 are swapped, etc).

shift all odd bits left for 1 position and shift all even bits right for 1 position

public class SwapBits {
 public int swapBits (int n) {
   //0xaaaaaaaa = 10101010...10
   // 0x55555555 = 1010101...01
   return (n & 0xaaaaaaaa) >> 1 | (n & 0x55555555) << 1;
 }
}

Monday, December 15, 2014

Single number I & II &III

Single Number

Given an array of integers, every element appears twice except for one. Find that single one.

Bitwise operations.

Single number I
Using XOR operation. Because each number appears twice, XOR cancels out them except the single number.

public class SingleNumber {
    public int singleNumber(int[] A) {
        int rst = 0;
        for (int i = 0; i < A.length; i++)
            //XOR
            rst ^= A[i];
        return rst;
        
    }
}

Single Number II

Given an array of integers, every element appears three times except for one. Find that single one.

Count each of the 32 bit of every element. Then mod each bit by 3, this operation will cancels out all numbers that appear three times.

Update: 2015 - 01 - 03

I put the array iteration at the outer loop at first, then I realize it will need an extra iteration to do the mod and add bits back.
Loop the bits first allows us to get the result in one pass.

public class Solution {
    public int singleNumber(int[] A) {
        if (A == null || A.length == 0)
            return -1;
        //unsigned int, 32 bits
        int[] bits = new int[32];
        int rst = 0;
        for (int i = 0; i < 32; i++)
        {
            for (int j = 0; j < A.length; j++)
            {
                // & 1 will count only the bit 1
                bits[i] += A[j] >> i & 1;
                bits[i] %= 3;
            }
            //adding back to the original position by left shift i bits. 
            //e.g.  000 = 000 || (1 << 2) = 100
            rst |= (bits[i] << i);
        }
        return rst;
        
    }
}

Single Number III

Given an array of numbers nums, in which exactly two elements appear only once and all the other elements appear exactly twice. Find the two elements that appear only once.
For example:
Given nums = [1, 2, 1, 3, 2, 5], return [3, 5].
Note:
  1. The order of the result is not important. So in the above example, [5, 3] is also correct.
  2. Your algorithm should run in linear runtime complexity. Could you implement it using only constant space complexity?


Similar to the first problem, we use xor. Now after the first traversal, we have a number n that is the xor of the two single numbers. We then try to find the first different bit from the number. Then we traverse the array again, now we xor all numbers with that bit equals 1, for all numbers that appear twice, they will be cancel out. This operation will also cancel one of the two single numbers with that bit equals 1. Now the rest of n is the first number and we use xor to find the second number.


    public int[] singleNumber(int[] nums) {
        int[] rst = new int[2];
        if (nums == null || nums.length < 2)
            return rst;
        int xor = 0;
        for (int n : nums) 
            xor ^= n;
        
        int first_different_bit = 0;
        for (first_different_bit = 0; first_different_bit < 32; first_different_bit++) {
            if (((xor >> first_different_bit) & 1) == 1)
                break;
        }
        
        int num1 = 0;
        for (int n : nums) {
            if (((n >> first_different_bit) & 1) == 1)
                num1 ^= n;
        }
        rst[0] = num1;
        rst[1] = xor ^ num1;
        return rst;
    }