find the different rightmost bit - xor

I am stuck on this problem. Thanks for your assistance.
You're given two integers, n and m. Find position of the rightmost bit in which they differ in their binary representations (it is guaranteed that such a bit exists), counting from right to left.
Return the value of 2position_of_the_found_bit (0-based).
Example
For n = 11 and m = 13, the output should be
differentRightmostBit(n, m) = 2.
11 (subscript 10) = 1011 (subscript 2), 13 (subscript) 10 = 1101 (subscript 2), the rightmost bit in which they differ is the bit at position 1 (0-based) from the right in the binary representations.
So the answer is 2 to the 1st power = 2.

After playing around with the bitwise operators I got it !! the answer is (n ^ m) & -(n ^ m)
I could have easily done this in ruby without using the bitwise operators by converting them to a binary string and finding the first non - match starting on the right side and returning (2 ** position) but it was required to be a one liner using the bitwise operators that was the tricky part.
I give credit to Ryan for pointing me in the right direction. Thanks Ryan !!

Since all integers are stored in a 32 bit register hence we need to check value in all these 32 registers now since at 32th register we require 1 from right so 33-32=1 hence at last 33-a[k-1] for the answer. Here i just stored the positions where the binary value is unequal in array 'a' and printed the last element in the array would even work for -ve integers.
#include <iostream>
using namespace std;
int main()
{
int n,m,k=0,y=0;
cin>>n>>m;
int a[32];
for(int i=31;i>=0;i--)
{
y=y+1;
if(n & (1<<i))
{if( !(m & (1<<i)) )
{
a[k]=y;
k++;
}
}else
if ( !(n & (1<<i)) )
{if (m & (1<<i))
{
a[k]=y;
k++;
}
}
}
cout<<33-a[k-1];
return 0;
}

The answer of your question is the below code written in java.The input of this code is in following format:
Input:
First line of input contains a single integer T which denotes the number of test cases. T test cases follows. First line of each test case contains two space separated integers M and N.
Example:
Input:
2
11 9
52 4
Output:
2
5
In binary "11" is "1011"
and "9" is "1001" and as you can see the 2nd bit(from R.H.S) is different and that should be our answer.
import java.io.IOException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
//sourabh agrawal
class GFG {
public static void main(String[] args)throws IOException{
final BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int t = Integer.parseInt(br.readLine().trim());
StringBuilder sb = new StringBuilder();
while(t-->0){
StringTokenizer st = new StringTokenizer(br.readLine().trim());
int a = Integer.parseInt(st.nextToken().trim());
int b = Integer.parseInt(st.nextToken().trim());
int c = (a^b)&-(a^b); //this is the key to solve the question
String ans = Integer.toBinaryString(c);
int size = ans.length();
int position = 1;
while(size-->0){
if(ans.charAt(size)=='0'){
position++;
}else{
break;
}
}
sb.append(position).append("\n");
}
System.out.println(sb);
}
}

One More way:
int RightMostDiffBit(int M,int N){
int count = 1;
for(int i=0;i<32;i++){
if((M & (count << i)) ^ (N & (count << i)))
return i+1;
}
return -1;
}

int main()
{
int a,b,i=0, tempa,tempb;
printf("enter values for elements a and b\n");
scanf("%d %d", &a,&b);
while(i<=31)
{
tempa= a&(1<<i);
tempb= b&(1<<i);
if((tempa^tempb))
{
printf("pos of different bit is %d\n",i);
break;
}
i++;
}
return 0;
}

Related

Shortest way to go from decimal string to decimal of binary mirror?

I have a text file with a list of decimals. I need to print to another file a list of decimals which are the base 10 of the binary mirrors of the original numbers. Currently I'm doing it like this (where each step is one function):
decimal strings -> number array -> binary strings -> base 10 of binary mirror
Is there a much shorter number of steps I could have taken that I failed to see or does this make sense?
Assuming you have a 32-bit integer, you can revert the bits by doing:
#include <stdio.h>
void printBinary(int x)
{
int m = 0x80000000;
while(m)
{
printf("%d", (m & x) ? 1 : 0);
m = m >> 1;
m = m & 0x7fffffff;
}
printf("\n");
}
int binaryReverse(int x)
{
int i = 0;
int t = 0;
int m = 0x80000000;
while(m)
{
if (m & x)
{
t = t | (1 << i);
}
++i;
m = m >> 1;
m = m & 0x7fffffff;
}
return t;
}
int main(void) {
int x = 19088743;
printf("%u\n",x);
printBinary(x);
int y = binaryReverse(x);
printf("%u\n",y);
printBinary(y);
return 0;
}
Output:
19088743
00000001001000110100010101100111
3869426816
11100110101000101100010010000000
You don't need to convert to strings of ASCII "1"s and "0"s (what I assume is meant by "binary strings") for that-- you can use bitwise operators. You can omit the "binary strings" step.
Note that "binary mirror" is an unclear term, however googling it may lead you to find the real name for what you actually want to do.

C: Decimal Value

Can any one help me sort out one problem, i have to reverse a number without using array(int/char) for storing them.
input1 = 123
output1 = 321
input2 = 2300
output2 = 0032
I am trying to find the solution but 0 got erased while printing so i thought of octal conversion but still no solution, so i went with the decimal places and i made the 23 to 0.0032. Now my problem is how can i extract the 0032 from that part.
Is there any possible way to achieve this without using array(int/char), with that it will be easy.
#include<stdio.h>
#include<math.h>
int main()
{
int number =3200;
int temp;
while (number >0)
{
temp= number%10;
printf("%d",temp);
number = number/10;
}
return 0;
}
you could use recursion to solve this problem, without using any array in fact u could also reverse a string without using any array using recursion. This code works for both numbers and strings and it has no arrays:
char reverse(int a)
{
char c,d;
if(a=='\n')
return 0;
c=getchar();
d=reverse(c);
putchar(a);
return (c);
}
int main()
{
char c;
scanf("%c",&c);
reverse(c);
}
for a start try this.
int n, l;
char nBuf[126];
n = 1230010;
l = sprintf(nBuf, "%d", n );
while( l >= 0 )
printf("%c", nBuf[l--] );
Though if you are taking input from stdin take it as string rathar than as int or long.
Edit - for not using array
int n = 123;
while(n) {
printf("%d", n%10);
n/=10;
}
I am assuming to get a value of this sort "output2 = 0032" it is better of being a string, else formatting complications turns up with input value length and format left space with zeros etc etc.
This becomes fairly easy if you know that you can represent numbers like so:
x = a_0 + a_1 * b^1 + a_2 * b^2 + ...
a_i are the digits
b is the base
To extract the lowest digit, you can use the remainder: x % b
Dividing by the base "removes" the last digit. That way you can get the digits in order lowest to highest.
If you reverse the digits then the lowest becomes the highest. Looking at below transformation it's easy to see how to incrementally build up a number when the digits come in order highest to lowest:
x = a_0 + b * (a_1 + b * (a_2 + ...
You start of with 0, and for each digit you multiply with the base and then add the digit.
In pseudo code:
output = 0
while input != 0
digit = input % base
input = input / base ;; integer division
output = output * base + digit
end
If you want to store leading zeros, then you need to either store the digits in an array, or remember for how many steps of above loop the output remained zero:
output = 0
zeros = 0
while input != 0
digit = input % base
input = input / base ;; integer division
output = output * base + digit
if output == 0
zeros = zeros + 1
end
end
To print that you obviously need to print zeros zeros and then the number.
Live example here, relevant code:
unsigned reverse(
unsigned input,
unsigned const base,
unsigned * const zeros) {
unsigned output = 0;
unsigned still_zero = 0;
for (; input != 0; input/=base) {
output *= base;
output += input % base;
if (output == 0) {
++still_zero;
}
}
if (zeros != NULL) {
*zeros = still_zero;
}
return output;
}
void print_zeros(unsigned zeros) {
for (; zeros != 0; --zeros) {
printf("0");
}
}
Recursion allows for a simple solution. A small variation on #vishu rathore
void rev_dec(void) {
int ch = getchar();
if (isdigit(ch)) {
rev_dec();
}
if (ch >= 0) putchar(ch);
}
int main(void) {
rev_dec();
return 0;
}
input
0123456789012345678901234567890123456789
output
9876543210987654321098765432109876543210

Flip the bits in C

Recently in a interview i was asked the below question and i couldn't able to answer it correctly. Can some one please let me know what exactly the answer is.
Question:
You are given an array of size N. The elements of the array are d[0],d[1]...d[N-1] where each d[i] is either 0 or 1. You can perform at most one move on the array :choose any two integers [L,R] and flip all the elements between (and including) the Lth and Rth bits. L and R represent the left most and the right most index of the bits marking the boundaries of the segment which you have decided to flip.
What is the maximum number if 1 - bits (indicated by S) which you can obtain in the final bit string? 'Flipping ' a bit means , that a 0 is transformed to a 1 and a 1 is transformed to a 0.
sample input
8
10010010
sample output
6
How about this? I'm assuming that the definition of [L,R] is inclusive, so that if L=5 and R=2, you want to flip bits 2-5, inclusive.
Basically, you construct a mask which has 1's in the positions to be flipped, and then XOR it with the original integer.
int d = 0xdeadbeef; /* 0b11011110101011011011111011101111 */
int l = 5;
int r = 2;
int mask = 0;
for (int ii=r; ii<=l; i++) {
mask |= 1<<ii;
}
printf("Original: %x", d);
printf("Bits %d-%d flipped: %x", r, l, d^mask) /* 0b11011110101011011011111011010011 */
Here is a complete solution to the OP's revised question: I've written it in Python 2.7 rather than C because:
This is an algorithmic question, and the language-specific details are relatively unimportant.
Python has a really nice bitstring module for manipulation of arbitrary-length bit-strings.
I don't want to do the OP's homework totally for him.
This algorithm is O(N^2): it's the brute-force approach I suggested in my comment above. It simply looks at all the substrings of the original string, and finds the one which has the greatest imbalance of 0s and 1s (maximum N_0 - N_1). It uses a half-open definition of the interval [L,R) since this is the most natural notation with Python's slicing syntax.
import bitstring
def maximize_ones(s):
best = lbest = rbest = 0
for ledge in range(0,len(s)-1):
for redge in range(ledge+1,len(s)):
if redge-ledge<=best:
continue
value = s[ledge:redge].count(0)-s[ledge:redge].count(1)
if value>best:
best = value
lbest = ledge
rbest = redge
# Uncomment to show intermediate best-so-far solutions
# print "Flipping bits [%d,%d) will add %d additional 1s" % (lbest, rbest, best)
return best, lbest, rbest
s = bitstring.Bits(bin=raw_input("Bit string:"))
d = len(s)
best, lbest, rbest = maximize_ones(s)
best_mask = bitstring.Bits(bin=('0'*lbest)+('1'*(rbest-lbest))+('0'*(len(s)-rbest)))
print "Flipping bits [%d,%d) will add %d additional 1s" % (lbest, rbest, best)
print " s_orig = %s (contains %d ones)" % (s.bin, s.count(1))
print " s_flip = %s (contains %d ones)" % ((s^best_mask).bin, (s^best_mask).count(1))
Example output:
$ python maximize_ones.py
Bit string:101100101001000010100010
Flipping bits [4,22) will add 8 additional 1s
s_orig = 101100101001000010100010 (contains 9 ones)
s_flip = 101111010110111101011110 (contains 17 ones)
I did it C Language:
int elementsCount = 0;
printf("Specify number of elements in arry:\n");
scanf("%d",&elementsCount);
int arrayValue [elementsCount];
printf("Enter elementsCount numbers:\n");
for(int i=0;i<elementsCount;++i)
{
scanf("%d",&arrayValue[i]);
}
printf("Given Elements of Array are :\n");
for(int j=0;j<elementsCount;++j)
{
printf("%d",arrayValue[j]);
}
printf("\n");
int lValue,rValue;
int count = sizeof(arrayValue)/sizeof(arrayValue[0]);
int onesCount = 0;
printf("Specify LeftIndex Range :\n");
scanf("%d",&lValue);
printf("Specify LeftIndex Range :\n");
scanf("%d", &rValue);
for (int i=0;i<count;i++)
{
if (i >=lValue && i<=rValue)
{
int flipValue = arrayValue[i];
if (flipValue == 0)
{
arrayValue[i] = 1;
}
else if(flipValue == 1)
{
arrayValue[i] = 0;
}
}
}
for (int k =0;k<count; k++)
{
printf("%d",arrayValue[k]);
if (arrayValue[k] == 1)
{
onesCount = onesCount + 1;
}
}
printf("\n");
printf("Total Number of 1's are: %d\n",onesCount);

Transpose function, decimal to binary

i am trying to develop a transpose function which can transpose from decimal to binary an up to 9digits number. I'm pretty new on coding and this is my first try. But it does not seem to be working, sorry if i am asking something obvious, but i need some help. Thanks in advance.
void transpose(int n)
{
int c, k;
for (c = 31; c >= 0; c--)
{
k = (n % c);
if (k == 0) printf("1");
else printf("0");
}
}
Instead of using arithmetic operations, you could use bitwise operations and get the digit directly:
for (c = 31; c >= 0; --c)
{
printf("%d", (n >> c) & 1);
}
This shifts the value in n right by c steps, i.e. putting bit number c in the rightmost (least-signigficant) bit. Then the mask with 1 will result in either a one or a zero, which is then printed.
#include <stdio.h>
#include <limits.h>
void transpose(int n){
unsigned x;
char bits[CHAR_BIT * sizeof(n)+1];
char *p = bits + CHAR_BIT * sizeof(n);
*p = '\0';
for(x=n; p!=bits ;x>>=1)
*--p = "01"[x & 1];
puts(bits);
}
Debugging your program for n = 5:
When c becomes 5, 1 get printed after 26 0's
000000000000000000000000001
now for rest of c (till 0), the output is
00000000000000000000000000100000
and unfortunately this is not 5 in decimal. Hope you understand what you are doing wrong.
You are checking whether a number n is divisible by all numbers 31 to 0. This is not what you need to do to convert the base.
Where a decimal representation shows you a number, for instance, 6174 (kapreka constant)
as able to be built up out of these blocks:
4 * 10^0
7 * 10^1
1 * 10^3
6 * 10^4
0*..
0*..
you would want your transpose function to result in a representation of powers of 2. I hope this helps directing you to an answer.

Finding consecutive bit string of 1 or 0

How to find the length of the longest consecutive bit string(either 1 or 0)?
00000000 11110000 00000000 00000000 -> If it is 0 then length will be 20
11111111 11110000 11110111 11111111 -> If it is 1 then length will be 12
The following is based on the concept that if you AND a bit sequence with a shifted version of itself, you're effectively removing the trailing 1 from a row of consecutive 1's.
11101111 (x)
& 11011110 (x << 1)
----------
11001110 (x & (x << 1))
^ ^
| |
trailing 1 removed
Repeating this N times will reduce any sequence with N consecutive 1's to 0x00.
So, to count the number of consecutive 1's:
int count_consecutive_ones(int in) {
int count = 0;
while (in) {
in = (in & (in << 1));
count++;
}
return count;
}
To count the number of consecutive 0's, simply invert and the same routine.
int count_consecutive_zeros(int in) {
return count_consecutive_ones(~in);
}
Proof of concept: http://ideone.com/Z1l0D
int main(void) {
printf("%d has %d consecutive 1's\n", 0, count_consecutive_ones(0));
printf("%d has %d consecutive 0's\n", 0, count_consecutive_zeros(0));
/* 00000000 11110000 00000000 00000000 -> If it is 0 then length will be 20 */
printf("%x has %d consecutive 0's\n", 0x00F00000, count_consecutive_zeros(0x00F00000));
/* 11111111 11110000 11110111 11111111 -> If it is 1 then length will be 12 */
printf("%x has %d consecutive 1's\n", 0xFFF0F7FF, count_consecutive_ones(0xFFF0F7FF));
}
Output:
0 has 0 consecutive 1's
0 has 32 consecutive 0's
f00000 has 20 consecutive 0's
fff0f7ff has 12 consecutive 1's
One simple way would be to simply loop over the bits, and keep track of the number of bits in a row which have had the same value, and the maximum that this value has reached.
Here's a simple C function which does just this:
int num_conseq_matching_bits(int n) {
int i, max, cur, b, prevb;
prevb = n & 1; /* 0th bit */
cur = 1;
max = 1;
for(i=1; i<32; i++) {
b = (n >> i) & 1; /* get the i'th bit's value */
if(b == prevb) {
cur += 1;
if(cur > max)
max = cur;
}
else {
cur = 1; /* count self */
prevb = b;
}
}
return max;
}
You can form a look up table to do it quickly for you. The bigger the table, the faster the lookup. 2x256 entry tables can do 8 bits at a time with a little bit twiddling. Add a 1s version of the table and start adding entries. That's probably how I'd go about it.
To use the table idea, you need something like
static struct {
int lead; /* leading 0 bits */
int max; /* maximum 0 bits */
int trail; /* trailing 0 bits */
} table[256] = { ....data.... };
int mostConsecutiveBits(unsigned char *str, int length, bool count_ones) {
int max = 0; /* max seen so far */
int trail = 0; /* trailing 0s from previous bytes */
while (length-- > 0) {
int byte = *str++;
if (count_ones)
byte ^= 0xff;
if (table[byte].max > max)
max = table[byte].max;
if (trail + table[byte].lead > max)
max = trail + table[byte].lead;
if (byte)
trail = table[byte].trail;
else
trail += 8;
}
return max;
}
initializing the table is straight-forward, but depends on your bit- and byte-ordering (little endian or big endian).
Since you didn't wrote what is bit string (regular int, byte array or char string I've assumed that it's char array
int maxConsBits(char *pStr,char cChar)
{
char curChar;
int curMax = 0;
int max = 0;
while (pStr)
{
if (*pStr == cChar)
{
curMax++;
if (curMax > max)
{
max = curMax;
}
}
else
{
curMax = 0;
}
pStr++;
}
return max;
}
Posting from iPhone withbig fingers.
If ones, then invert.
Loop over the input using a leadz function. For each iteration, shift the input to the left. Continue until you reach the end of the input. Note that you need to compare the original input length with the cumulative leadz counts.
Also, as an optimization, you can early abort when the remaining input length is less than the largest leadz you have seen.
There are many fast leadz algorithms online.
I don't agree with the tables idea, because I was trying it and realized that even though "BA" in ASCII would contain 5 consecutive 0's for 'B' and 5 consecutive 0's for 'A', they will not add together for 10 consecutive 0's. As a matter of fact, there would be 5 consecutive 0's maximum. (This was in reference to a simple "counting bits in a table idea." Chris Dodd has since expounded on how a table could be used accurately.)
I would use an algorithm like this:
#include <iostream>
#include <algorithm>
using namespace std;
// Assumes Little Endian architecture
int mostConsecutiveBits(char str[], int length) {
int currentConsecutiveBits=0;
int maxConsecutiveBits=0;
char currentBit;
char lastBit=0;
char currentChar=str[0];
int charCtr,bitCtr;
for (charCtr=length-1; charCtr>=0; charCtr--) {
currentChar=str[charCtr];
for (bitCtr=0; bitCtr<8; bitCtr++) {
currentBit=currentChar & 1;
if (currentBit!=lastBit) {
maxConsecutiveBits=max(maxConsecutiveBits,currentConsecutiveBits);
currentConsecutiveBits=1;
lastBit=currentBit;
}
else {
currentConsecutiveBits++;
}
currentChar=currentChar>>1;
}
maxConsecutiveBits=max(maxConsecutiveBits,currentConsecutiveBits);
}
return maxConsecutiveBits;
}
int main (int argc, char * const argv[]) {
cout << mostConsecutiveBits("AB",2);
return 0;
}
In this algorithm, I assume the bitstream is represented as 8-bit characters. For each character, I look at the very last bit with a bitwise AND. If it's the same as the last bit, then I up the consecutive bit count, otherwise, I reset the count because the bits are no longer consecutive. I then use a bitwise shift operation to move the next bit in the character over for observation. Hope this helps!
My answer is effectively a duplicate of David Underhill's answer. :)
If you're just looking for a byte string of four bytes, you can pack these into an unsigned long and use an algorithm like this:
int CountConsecutiveOnes(unsigned long n)
{
unsigned long m = n;
int k = 0;
while (m)
{
++k;
n >>= 1;
m &= n;
}
return k;
}
For counting zeros, just taking the bitwise complement first.
If you need to count byte strings longer than four, you can just implement the operations x >>= 1 and x & y either directly on the byte strings or it may be more efficient to use strings of unsigned long so the carry checks on the implementation of x >>= 1 aren't too expensive.
It may help you....
First convert your binary number to String say bits.
It will give you max number of consecutive 1's (in java)
String[] split = bits.split("0");
Arrays.sort(split);
int maxLength = split[split.length - 1].length();
public static int maxConsecutiveOneInBinaryNumber(int number) {
int count = 0;
int max = 0;
while (number != 0) {
if ((number & 1) == 1) {
count++;
} else {
max = Math.max(count, max);
count = 0;
}
number = number >> 1;
}
return Math.max(count, max);
}
You can this code here:
https://github.com/VishalSKumar/DSFiddle/blob/master/src/main/java/com/vishalskumar/hackerrank/MaxConsecutiveOneInBinary.java

Resources