Count number of adjacent pairs in Binary - c

Let's say that I'm given an integer n, which is read from the user.
I would like to count the number of adjacent pairs of 1's that is has.
So for example, let's say I'm given the number 31.
The binary representation of 31 is 11111.
The number of pairs would be 11 11 1 => 2 pairs
How would you do this using bitwise operators?
Thanks!

You have to validate the integer with the ((n&3)==3) condition to find an adjacent pairs in bit position 0 and 1. If pair found we shift to right by 2 otherwise by 1 until we did not check all of the 32 bits.
unsigned int n = 31; /* input */
unsigned char number_of_pairs = 0; /* result */
unsigned char mask_position = 0;
do
{
if(((n >> mask_position) & 3) == 3)
{
number_of_pairs += 1;
mask_position += 2;
}
else
{
mask_position += 1;
}
} while(mask_position < 32);

Related

Recursion function to check if bit is set or not (1\0)

I have this template and I need to fill the empty places, the function needs to return (count) the number of set (1) bits in a number (x)
In this question, an int is 2 bytes aka 16 bits
Template:
int dlukim(int x, int n, int count)
{
if (n > 16)
(1); // return count;
else
{
if ( (2) ) count++;
(3);// n++;
dlukim((4), n, count) // x
}
}
What's after the // is what I think should fill the empty space and I just don't know what to do on empty space number 2.
This is quite contrived, but something like this:
int count_ones(unsigned int x, int count)
{
/* Base case: zero has no further bits set. */
if (x == 0)
return count;
return count_ones(x >> 1, count + (x & 1));
}
int main(void)
{
const unsigned int x = 0xfeedf00du;
printf("%u has %d\n", x, count_ones(x, 0));
return 0;
}
Not sure about the n argument, could be used to track which bit to inspect but I optimized it out and always inspect bit 0, using right-shift between recursive steps to move all bits through that position.
I also switched x to unsigned int since that's more "clean" when caring about the bits in my opinion.
So first of all, int is 4 bytes which are 32 bits. But for 16 bits integer the code should look like the following:
if (n > 16)
return count;
else {
if (x % 2 == 1) count++;
n++;
set_bits(x/2, n, count);
}
Dividing a number by 2 means moving it to the right side by 1 bit. If x % 2 is 1 - the current bit is set, for example consider the decimal number 7 which is 111 in it's binary representation, 7 % 2 = 1 and 7 / 2 = 3 which is 11 in binary, and so on...

Binary decimal conversion with arrays

Do you have a simple idea of how we go from a binary number to a decimal number in C without doing any divisions (because I can have very big numbers), maybe only with masks (&, |, << or >>) .
I have a table like this:
tab[20] = {1,0,0,1,0,0,0,1,1,0,0,1,0,0,0,1,1,1,0,1};
and I would like this :
tab[6] = {5,9,6,2,5,3};
Is this something that can be done ? Thank you for your help
idea of how we go from a binary number to a decimal number (can have very big numbers)
For each binary digit, scale the decimal destination by 2 and add the digit.
Pseudo code
some_integer_type tab2[] = {1,0,0,1,0,0,0,1,1,0,0,1,0,0,0,1,1,1,0,1};
some_integer_type tab10[big_enough];
zero fill tab10[]
for (each i element in tab2[] starting with index 0) {
// scale tab10[] by 2 and add tab2[]
carry = tab2[i]
for (each j element in tab10[] starting with the last index) {
sum = (tab10[j] << 1) | carry;
if (sum >= 10) {
sum -= 10;
carry = 1;
} else {
carry = 0;
}
tab10[i] = sum;
}
}
print tab10[]
To do >=, -= 10 with only &, |, << or >>, create helper functions: divide and conquer.
No division and up to 64 bit. This is "big". The bin-to-dec is done with sprintf(). That digit-string can then be converted to an array of integers like your tab[6]
char bittab[64] = {1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0};
long num = 0, dupl = 1;
int i;
for (i = 0; i < sizeof bittab; i++) {
num += dupl * bittab[i];
dupl *= 2;
}
char decstring[30];
sprintf(decstring, "%ld\n", num);
for (i = 0; i < strlen(decstring); i++)
printf("%d\n", decstring[i] - '0');
The output is:
3
2
7
6
7
-38
This can be written into a dectab[] array, excluding the null terminator byte.
(I made the bits ascending to leave the size open.)

Determine a function to extract the individual digits of a long data type without using arrays and use only loops or conditionals

I am trying to determine a function to extract the individual digits of a long data type which the user enters.
int remain(int digit)
{
while(number != 0)
{
digit = number % 10;
number = number / 10;
}
return digit;
}
In this code the number variable is the number entered by user.
I want to extract all the digits of the number (e.g. a 16 digit number). So when I print remain(16) it prints 16 instead of 16th digit or prints 1 if I print remain(1). And also it prints the first digit if the number is less than 13 or greater than 16 and prints the 1 or 2 or 3 if i print remain(1) or remain(2) or remain(3) instead of printing the 1st or 2nd or 3rd digit, if the number is 13 digit long or 16 digit long or 15 digit long.
Okay, after your edit, I understand you want to print the return of the function and have all digits print. While you can simply use printf(), extracting with % and / is another way to extract digits. But, as you have found, when you extract digits with % and /, the digits will end up in reverse order. The solve that problem, you simply fill an array with digits, working from the end of the array back to the beginning.
Now before looking at a solution, if you want to "... extract the individual digits of a long data..." -- you will need to change the type in your function from int to long or you will experience a mismatch of type-size on systems where int and long are different sizes (like on x86_64).
In order for the array to survive the return of your function, you can either pass in an array to fill using another parameter, or you can declare your array with static storage duration so it survives return (but not that make the function not thread_safe in multithreaded programs -- not a concern here)
You can do something like the following:
#include <stdio.h>
#include <stdlib.h>
#define NCHR 32 /* if you need a constant, #define one (or more) */
#define BASE 10
char *extract_digits (long n)
{
static char digits[NCHR]; /* static, so digits survives return */
char *p = digits + NCHR - 1; /* pointer to last char in digits */
int sign = n < 0; /* check sign of n (negative, sign == 1) */
if (sign) /* process positive number */
n = -n;
if (!n) { /* handle zero case, sign irrelevant */
*--p = '0';
return p;
}
do { /* convert each digit to char */
*--p = n % BASE + '0'; /* fill from end of digits array */
n /= BASE;
} while (n);
if (sign) /* if sign, add '-' at front */
*--p = '-';
return p; /* return ptr to start of digits in digits[] */
}
int main (int argc, char **argv) {
long v = argc > 1 ? strtol(argv[1], NULL, BASE) : -2381;
printf ("digits: %s\n", extract_digits(v));
}
(note: I have change the function name to extract_digits(), you can rename it as you please)
The program prints the extracted digits directly using the function return -- which is what I take was your intent from the question.
Example Use/Output
Using default value:
$ ./bin/extractdigits_fnc
digits: -2381
Passing value:
$ ./bin/extractdigits_fnc 54823
digits: 54823
Passing zero:
$ ./bin/extractdigits_fnc 0
digits: 0
Passing negative zero:
$ ./bin/extractdigits_fnc -0
digits: 0
Your '16' example:
$ ./bin/extractdigits_fnc 16
digits: 16
Look things over and let me know if I understood your question correctly.
If you are looking for a function that can extract the n'th digit in a number, it can be something like:
int extract_digit(unsigned long long number, unsigned digit)
{
int res = -1;
if (digit > 0)
{
unsigned count = 1;
unsigned long long tmp = number;
while(tmp/10 > 0)
{
++count;
tmp /= 10;
}
if (digit <= count)
{
tmp = number;
while ((count - digit) > 0)
{
--count;
tmp /= 10;
}
res = tmp % 10;
}
}
return res;
}
Notice that the function assumes that the left-most digit is digit 1.
The function will return a -1 if the requested "digit" doesn't exists. Otherwise the function returns the digit.
The function can be used like:
int main(void){
unsigned long long number = 31415926535ULL;
printf("number: %llu\n", number);
for (unsigned i = 0; i < 13; ++i)
{
int n = extract_digit(number, i); // Get i'th digit
if (n < 0)
{
printf("Digit %u is out of range\n", i);
}
else
{
printf("Digit %u is %d\n", i, n);
}
}
return 0;
}
Output
number: 31415926535
Digit 0 is out of range
Digit 1 is 3
Digit 2 is 1
Digit 3 is 4
Digit 4 is 1
Digit 5 is 5
Digit 6 is 9
Digit 7 is 2
Digit 8 is 6
Digit 9 is 5
Digit 10 is 3
Digit 11 is 5
Digit 12 is out of range

Logic to check the number is divisible by 3 or not?

without using %, / or * , I have to find the no. is divisible by 3 or not?
it might be an interview question.
Thanks.
There are various ways. The simplest is pretty obvious:
int isdivby3(int n) {
if (n < 0) n = -n;
while (n > 0) n -= 3;
return n == 0;
}
But we can improve that. Any number can be represented like this: ("," means range inclusive):
Base2 (AKA binary)
(0,1) + 2*(0,1) + 4*(0,1)
Base4
(0,3) + 4*(0,3) + 16*(0,3)
BaseN
(0,N-1) + N*(0,N-1) + N*N*(0,N-1)
Now the trick is, a number x is divisible by n-1 if and only if the digitsum of x in base n is divisible by n-1. This trick is well-known for 9:
1926 = 6 + 2*10 + 9*100 + 1*1000
6+2+9+1 = 8 + 1*10
8+1 = 9 thus 1926 is divisible by 9
Now we can apply that for 3 too in base4. And were lucky since 4 is a power of 2 we can do binary bitwise operations. I use the notation number(base).
27(10) = 123(4)
Digitsum
12(4)
Digitsum again
3(4) = Divisible!
Now let's translate that to C:
int div3(int n) {
if (n < 0) n = -n;
else if (n == 0) return 1;
while (n > 3) {
int d = 0;
while (n > 0) {
d += n & 3;
n >>= 2;
}
n = d;
}
return n == 3;
}
Blazing fast.
Subtract 3 until you either
hit 0 - number was divisible by 3 (or)
get a number less than 0 - number wasn't divisible
if (number > 0)
{
while (number > 0)
{
number -= 3;
}
}
else if( number < 0)
{
while number < 0:
number += 3
}
return number == 0
Here is a reasonably efficient algorithm for large numbers. (Well not very efficient, but reasonable given the constraints.)
Use sprintf to convert it to a string, convert each digit back to a number. Add up the digits. If you come up with 3, 6, or 9, it is divisible by 3. Anything else less than 10, it is not. Anything over 9, recurse.
For instance to test the number 813478902 you'd stringify, then add the digits to get 42, add those digits to get 6, so it is divisible by 3.
just use a for loop subtracting 3 over and over and see if you get to 0. if you get to negative without getting to 0 then you know its not divisible by 3
To print a count sequence which is divisible by 3 without division or modulus operator.
Notice the count sequence:
00: 00(00)
01: 0001
02: 0010
03: 00(11)
04: 0100
05: 0101
06: 01(10)
07: 0111
08: 1000
09: 10(01)
10: 1010
11: 1011
12: 11(00)
13: 1101
14: 1110
15: 11(11)
16: 10000
17: 10001
18: 100(10)
19: 10011
20: 10100
21: 101(01)
Note that the last two bits of those numbers which are divisible by three (shown in brackets) are cycling through {00, 11, 10, 01} . What we need to check is if the last two bits of the count sequence has these bits in a sequence.
First we start matching with mask = 00 and loop while the first number is not encountered with the lower two bits 00. When a match is found we then do (mask + 03) & 0x03 which gets us the next mask in the set. And we continue to match the last two bits of the next count with 11. Which can be done by ((count & 3) == mask)
The code is
#include <stdio.h>
int main (void)
{
int i=0;
unsigned int mask = 0x00;
for (i=0; i<100;i++)
{
if ((i&0x03) == mask)
{
printf ("\n%d", i);
mask = (mask + 3) & 0x03;
}
}
printf ("\n");
return 0;
}
This is not a general one. Best is to use the solution which #nightcracker have suggested
Also if you really want to implement the division operation i without using the divide operations. I would tell you to have a look at the Non-Restoring Division Algorithm, this can be done in program with a lot of bit manipulations with bitwise operators. Here are some links and references for it.
Wikipedia Link
Here is a demo from UMass
Also have a look at Computer Organization by Carl Hamacher, Zvonko Vranesic, Safwat Zaky
number = abs(number)
while (number > 0)
{
number -= 3;
}
return number == 0
Suppose n is the number in question and it is non-negative.
If n is 0 it is divisible by 3; otherwise n = (2^p)*(2*n1+1) and n is divisible by 3 iff 2*n1+1 is, iff there is a k>=0 with 2*n1+1 = 3*(2*k+1) iff n1 = 3*k+1 iff n1=1 or n1> 1 and n1-1 is divisible by 3. So:
int ism3( int n)
{ for(;n;)
{ while( !(n & 1)) n >>= 1;
n >>= 1;
if ( n == 0) return 0;
n-= 1;
}
return 1;
}
The simplest way to know if a number is divisible by 3 is to sum all its digits and divide the result by 3. If the sum of the digits is divisible by 3, so the number itself is divisible by 3. For instance, 54467565687 is divisible by 3, because 5+4+4+6+7+5+6+5+6+8+7 = 63, and 63 is divisible by 3. So, no matter how big is the number, you can find if it is divisible by 3 just adding all its digits, and subtracting 3 from the value of this sum until you have a result smaller than 3. If this result is 0, the value of the sum is divisible by 3 (and so the original number), otherwise the sum is not divisible by 3 (and the original number is not divisible, either). It's done much more quickly than subtract 3 successively from the original number (of course, specially if it is a large number) and with no divisions. Um abraço a todos.
Artur
A number is divisible by three if its binary alternating digit sum is zero:
bool by3(int n) {
int s=0;
for (int q=1; n; s+=q*(n&1), n>>=1, q*=-1);
return !s;
}
You could use user feedback:
int isDivisibleBy3(int n)
{
int areDivisibleBy3[] = {};
for(int i = 0; i < 0; i++)
{
if(n == areDivisibleBy3[i])
{
return 1;
}
}
return 0;
}
When a user reports a bug stating that a number that is divisble by 3 is not giving the correct result, you simply add that number to the array and increase the number i is compared to in the for loop condition.
This is great because then you never have to worry about numbers the user never uses.
Don't forget to add a unit test for whenever a user reports a bug!

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