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
Mr. X and His Shots
A cricket match is going to be held. The field is represented by a 1D plane. A cricketer, Mr. X has N favorite shots. Each shot has a particular range. The range of the ith shot is from Ai to Bi. That means his favorite shot can be anywhere in this range. Each player on the opposite team can field only in a particular range. Player i can field from Ci to Di. You are given the N favorite shots of M
View Solution →Jim and the Skyscrapers
Jim has invented a new flying object called HZ42. HZ42 is like a broom and can only fly horizontally, independent of the environment. One day, Jim started his flight from Dubai's highest skyscraper, traveled some distance and landed on another skyscraper of same height! So much fun! But unfortunately, new skyscrapers have been built recently. Let us describe the problem in one dimensional space
View Solution →Palindromic Subsets
Consider a lowercase English alphabetic letter character denoted by c. A shift operation on some c turns it into the next letter in the alphabet. For example, and ,shift(a) = b , shift(e) = f, shift(z) = a . Given a zero-indexed string, s, of n lowercase letters, perform q queries on s where each query takes one of the following two forms: 1 i j t: All letters in the inclusive range from i t
View Solution →Counting On a Tree
Taylor loves trees, and this new challenge has him stumped! Consider a tree, t, consisting of n nodes. Each node is numbered from 1 to n, and each node i has an integer, ci, attached to it. A query on tree t takes the form w x y z. To process a query, you must print the count of ordered pairs of integers ( i , j ) such that the following four conditions are all satisfied: the path from n
View Solution →Polynomial Division
Consider a sequence, c0, c1, . . . , cn-1 , and a polynomial of degree 1 defined as Q(x ) = a * x + b. You must perform q queries on the sequence, where each query is one of the following two types: 1 i x: Replace ci with x. 2 l r: Consider the polynomial and determine whether is divisible by over the field , where . In other words, check if there exists a polynomial with integer coefficie
View Solution →Costly Intervals
Given an array, your goal is to find, for each element, the largest subarray containing it whose cost is at least k. Specifically, let A = [A1, A2, . . . , An ] be an array of length n, and let be the subarray from index l to index r. Also, Let MAX( l, r ) be the largest number in Al. . . r. Let MIN( l, r ) be the smallest number in Al . . .r . Let OR( l , r ) be the bitwise OR of the
View Solution →