Showing posts with label Coding. Show all posts
Showing posts with label Coding. Show all posts

Thursday, August 4, 2011

Dutch National Flag Problem

Given `N' objects coloured red, white or blue, sort them so that objects of the same colour are adjacent, with the colours in the order red, white and blue.
The technique to solve this problem is three way partitioning ie representing Red with 0 , White with 1 and Blue with 2 . The variables are lo , mid , hi .
lo = 1st position where value is not 0 .
hi = 1st position from end where value is not 2 .
mid = position past lo where value is not 1 .
sourcecode :

Tuesday, August 2, 2011

Write a program to check the binary representation of an integer ispalindrome or not ?

Eg :
4 --To Binary--> 100 : Not palindrome
5 --To Binary--> 101 : palindrome
simple approach:
1. reverse the bits of given number. O(log(n))
2. compare both the numbers.  
3. if same then palindrome else not. source code:
#include <iostream>
using namespace std;

int reverse(int n)
{
int i = 0, j = n;
while(j)
i = (i << 1) | (j & 1);
j >>= 1;
}
return(i);
}
int main()
{
int rev , n=5;
rev = reverse(n);
rev==n?cout<<"palindrome":cout<<"not palindrome";
return 0;
}

Total Pageviews

Print