2's complement


Problem Statement :


Understanding 's complement representation is fundamental to learning about Computer Science. It allows us to write negative numbers in binary. The leftmost digit is used as a sign bit. If it is , we have a negative number and it is represented as the two's complement of its absolute value. Let's say you wrote down the 's complement representation for each -bit integer in the inclusive range from  to . How many 's would you write down in all?

For example, using an -bit byte rather than  bit integer, the two's complement of a number can be found by reversing all its bits and adding . The two's complement representations for a few numbers are shown below:

To write down that range of numbers' two's complements in  bits, we wrote 's. Remember to use  bits rather than  in your solution. The logic is the same, so the  bit representation was chosen to reduce apparent complexity in the example.

Function Description

Complete the twosCompliment function in the editor below. It should return an integer.

twosCompliment has the following parameter(s):
- a: an integer, the range minimum
- b: an integer, the range maximum

Input Format

The first line contains an integer , the number of test cases.

Each of the next  lines contains two space-separated integers,  and .

Output Format

For each test case, print the number of 's in the -bit 's complement representation for integers in the inclusive range from  to  on a new line.



Solution :



title-img


                            Solution in C :

In  C  :






#include<stdio.h>
long long num[34];
long long ONES[33];
void init()
{
	int i;
	ONES[0]=1;
	ONES[1]=2;
	num[0]=1;
	for(i=1;i<33;i++)
		num[i]=num[i-1]<<1;
	for(i=2;i<32;i++)
		ONES[i]=(ONES[i-1]<<1)+(num[i]-num[i-1])-1;
}

long long calc(int x)
{
	long long sum=0,temp=0;
	int i,j,k;
	if(x==0)
		return 0;
	for(i=0;i<33;++i)
	{
		if(x<num[i])
			break;
	}
	i--;
	sum=ONES[i];
	temp=x-num[i];
	return sum+calc(temp)+temp;
}

void solve(long long a,long long b)
{
	long long lo,hi,count;
	if(a<0)
	{
		a++;
		lo=calc(-a);
		lo=(32*(-a))-lo;
		lo+=32;
		a--;
	}
	else
	{
		if(!a)
		lo=calc(a);
		else
		lo=calc(a-1);
	}
	if(b<0)
	{
		if(b==-2)
			hi=32;
		else if(b==-1)
			hi=0;
		else	
		{	
		b+=2;
		hi=calc(-b);
		hi=(32*(-b))-hi;
		hi+=32;
		b-=2;
		}
	}
	else
		hi=calc(b);
	if(a<0&&b>0)
		count=hi+lo;
	else
	count=hi-lo;
	if(count<0)count=-count;
	printf("%lld\n",count);
}
int main()
{
	int t,a,b;
	init();
	scanf("%d",&t);
	while(t--)
	{
		scanf("%d %d",&a,&b);
		solve(a,b);
	}
	return 0;
}
                        


                        Solution in C++ :

In  C ++ :







#include<iostream>
#include<stdio.h>
#include<string.h>
using namespace std ;
#define INF (int)1e9

long long solve(int a)
{
 if(a == 0) return 0 ;
 if(a % 2 == 0) return solve(a - 1) + __builtin_popcount(a) ;
 return ((long long)a + 1) / 2 + 2 * solve(a / 2) ;
}

long long solve(int a,int b)
{
 if(a >= 0)
 {
  long long ret = solve(b) ;
  if(a > 0) ret -= solve(a - 1) ;
  return ret ;
 }
 long long ret = (32LL * -(long long)a) - solve(~a) ;
 if(b > 0) ret += solve(b) ;
 else if(b < -1)
 {
  b++ ;
  ret -= (32LL * -(long long)b) - solve(~b) ;
 }
 return ret ;
}

int main()
{
 int runs,a,b ;
 cin >> runs ;
 while(runs--)
 {
  cin >> a >> b ;
  long long ret = solve(a,b) ;
  cout << ret << endl ;
 }
 return 0 ;
}
                    


                        Solution in Java :

In  Java :








import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;

public class Solution {
	
	private static Map<Long, Long> onesCache = new HashMap<Long, Long>();
	
	private static long computeOnes(long n, long div) {
		long onesCount = 0;
		
		if (onesCache.containsKey(n))
			return onesCache.get(n);
		else if (n == 0)
			return 0;
		else if (n == 1)
			return 1;
		
		long a = n / div;
		long b = n % div;
		
		if (a == 1) {
			onesCount += b + 1;
			onesCount += computeOnes(div - 1, div >> 1);
		}
		onesCount += computeOnes(b, div >> 1);
		
		onesCache.put(n, onesCount);
		
		return onesCount;
	}
	
	private static long computeOnes(long n) {
		if (n < 0)
			return -n * 32 - computeOnes(-n - 1, 1<<30);
		else
			return computeOnes(n, 1<<30);
	}

	/**
	 * @param args
	 * @throws IOException 
	 */
	public static void main(String[] args) throws IOException {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		String line;
		
		try {
			line = br.readLine();
			int tests = Integer.parseInt(line);
			
			int[][] intervals = new int[tests][2];
			for (int i=0; i < tests; i++) {
				line = br.readLine();
				String[] tokens = line.split(" ");
				intervals[i][0] = Integer.parseInt(tokens[0]);
				intervals[i][1] = Integer.parseInt(tokens[1]);
			}
			
			for (int i = 0; i < intervals.length; i++) {
				int x = intervals[i][0];
				int y = intervals[i][1];
				
				if ((x > 0 && y > 0) || (x < 0 && y < 0)) {
					long n1 = computeOnes(x + (x > 0 ? -1 : 0));
					long n2 = computeOnes(y + (y < 0 ? +1 : 0));
					System.out.println(Math.abs(n1 - n2));
				} else {
					long n1 = computeOnes(x);
					long n2 = computeOnes(y);
					System.out.println(n1 + n2);
				}
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			br.close();
		}
	}

}
                    


                        Solution in Python : 
                            
In  Python3 :







t = int(input())

def gen(num):
    if num == '':
        return 0
    elif num == '1':
        return 1
    elif num == '0':
        return 0
    elif num[0] == '0':
        return(gen(num[1:]))
    else:
        return(int(num[1:],2)+1+gen(num[1:])+2**(len(num)-2)*(len(num)-1))
    
def func(a,b):
    if a < 0 and b >= 0:
        if a+b+1 == 0: return(32*(b+1))
        elif a+b+1 < 0: return(32*(b+1)+func(a,-(b+2)))
        else: return(32*(-a)+func(-a,b))
    elif a < 0 and b < 0:
        return(32*(b-a+1)-func(-b-1,-a-1))
    else:
        if a == 0:
            return gen(bin(b)[2:])
        return gen(bin(b)[2:]) - gen(bin(a-1)[2:])
    
for ts in range(t):
    a,b = input().strip().split();a,b = int(a),int(b)
    print(func(a,b))
                    


View More Similar Problems

Waiter

You are a waiter at a party. There is a pile of numbered plates. Create an empty answers array. At each iteration, i, remove each plate from the top of the stack in order. Determine if the number on the plate is evenly divisible ith the prime number. If it is, stack it in pile Bi. Otherwise, stack it in stack Ai. Store the values Bi in from top to bottom in answers. In the next iteration, do the

View Solution →

Queue using Two Stacks

A queue is an abstract data type that maintains the order in which elements were added to it, allowing the oldest elements to be removed from the front and new elements to be added to the rear. This is called a First-In-First-Out (FIFO) data structure because the first element added to the queue (i.e., the one that has been waiting the longest) is always the first one to be removed. A basic que

View Solution →

Castle on the Grid

You are given a square grid with some cells open (.) and some blocked (X). Your playing piece can move along any row or column until it reaches the edge of the grid or a blocked cell. Given a grid, a start and a goal, determine the minmum number of moves to get to the goal. Function Description Complete the minimumMoves function in the editor. minimumMoves has the following parameter(s):

View Solution →

Down to Zero II

You are given Q queries. Each query consists of a single number N. You can perform any of the 2 operations N on in each move: 1: If we take 2 integers a and b where , N = a * b , then we can change N = max( a, b ) 2: Decrease the value of N by 1. Determine the minimum number of moves required to reduce the value of N to 0. Input Format The first line contains the integer Q.

View Solution →

Truck Tour

Suppose there is a circle. There are N petrol pumps on that circle. Petrol pumps are numbered 0 to (N-1) (both inclusive). You have two pieces of information corresponding to each of the petrol pump: (1) the amount of petrol that particular petrol pump will give, and (2) the distance from that petrol pump to the next petrol pump. Initially, you have a tank of infinite capacity carrying no petr

View Solution →

Queries with Fixed Length

Consider an -integer sequence, . We perform a query on by using an integer, , to calculate the result of the following expression: In other words, if we let , then you need to calculate . Given and queries, return a list of answers to each query. Example The first query uses all of the subarrays of length : . The maxima of the subarrays are . The minimum of these is . The secon

View Solution →