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 :
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
Fibonacci Numbers Tree
Shashank loves trees and math. He has a rooted tree, T , consisting of N nodes uniquely labeled with integers in the inclusive range [1 , N ]. The node labeled as 1 is the root node of tree , and each node in is associated with some positive integer value (all values are initially ). Let's define Fk as the Kth Fibonacci number. Shashank wants to perform 22 types of operations over his tree, T
View Solution →Pair Sums
Given an array, we define its value to be the value obtained by following these instructions: Write down all pairs of numbers from this array. Compute the product of each pair. Find the sum of all the products. For example, for a given array, for a given array [7,2 ,-1 ,2 ] Note that ( 7 , 2 ) is listed twice, one for each occurrence of 2. Given an array of integers, find the largest v
View Solution →Lazy White Falcon
White Falcon just solved the data structure problem below using heavy-light decomposition. Can you help her find a new solution that doesn't require implementing any fancy techniques? There are 2 types of query operations that can be performed on a tree: 1 u x: Assign x as the value of node u. 2 u v: Print the sum of the node values in the unique path from node u to node v. Given a tree wi
View Solution →Ticket to Ride
Simon received the board game Ticket to Ride as a birthday present. After playing it with his friends, he decides to come up with a strategy for the game. There are n cities on the map and n - 1 road plans. Each road plan consists of the following: Two cities which can be directly connected by a road. The length of the proposed road. The entire road plan is designed in such a way that if o
View Solution →Heavy Light White Falcon
Our lazy white falcon finally decided to learn heavy-light decomposition. Her teacher gave an assignment for her to practice this new technique. Please help her by solving this problem. You are given a tree with N nodes and each node's value is initially 0. The problem asks you to operate the following two types of queries: "1 u x" assign x to the value of the node . "2 u v" print the maxim
View Solution →Number Game on a Tree
Andy and Lily love playing games with numbers and trees. Today they have a tree consisting of n nodes and n -1 edges. Each edge i has an integer weight, wi. Before the game starts, Andy chooses an unordered pair of distinct nodes, ( u , v ), and uses all the edge weights present on the unique path from node u to node v to construct a list of numbers. For example, in the diagram below, Andy
View Solution →