Decibinary Numbers
Problem Statement :
Let's talk about binary numbers. We have an n-digit binary number, b , and we denote the digit at index i (zero-indexed from right to left) to be bi. We can find the decimal value of using the following formula: For example, if binary number b = 10010, we compute its decimal value like so: Meanwhile, in our well-known decimal number system where each digit ranges from 0 to 9, the value of some decimal number, d, can be expanded in the same way: Now that we've discussed both systems, let's combine decimal and binary numbers in a new system we call decibinary! In this number system, each digit ranges from to (like the decimal number system), but the place value of each digit corresponds to the one in the binary number system. For example, the decibinary number represents the decimal number because: Pretty cool system, right? Unfortunately, there's a problem: two different decibinary numbers can evaluate to the same decimal value! For example, the decibinary number also evaluates to the decimal value : This is a major problem because our new number system has no real applications beyond this challenge! Consider an infinite list of non-negative decibinary numbers that is sorted according to the following rules: The decibinary numbers are sorted in increasing order of the decimal value that they evaluate to. Any two decibinary numbers that evaluate to the same decimal value are ordered by increasing decimal value, meaning the equivalent decibinary values are strictly interpreted and compared as decimal values and the smaller decimal value is ordered first. For example, and both evaluate to . We would order before because . Function Description Complete the decibinaryNumbers function in the editor below. For each query, it should return the decibinary number at that one-based index. decibinaryNumbers has the following parameter(s): x: the index of the decibinary number to return Input Format The first line contains an integer, q, the number of queries. Each of the next q lines contains an integer, x, describing a query. Constraints 1 <= q <= 10^5 1 <= x <= 10^16 Output Format For each query, print a single integer denoting the the xth decibinary number in the list. Note that this must be the actual decibinary number and not its decimal value. Use 1-based indexing. Sample Input 0
Solution :
Solution in C :
In C :
#include <stdio.h>
#include <stdlib.h>
#define MAX 500000
int get_i(long long*a,long long num,int size);
long long med(long long*a,int size);
long long dp[30][MAX],sum[MAX],two[30];
unsigned long long ten[30];
int main(){
int T,i,j,k;
long long x,y,z;
unsigned long long ans;
for(i=two[0]=ten[0]=1;i<30;i++){
two[i]=two[i-1]*2;
ten[i]=ten[i-1]*10;
}
for(i=0,dp[0][0]=1;i<MAX;i++)
for(j=1;j<30;j++)
for(k=0;k<10;k++)
if(k*two[j-1]<=i)
dp[j][i]+=dp[j-1][i-k*two[j-1]];
for(i=0;i<MAX;i++)
if(i)
sum[i]=sum[i-1]+dp[29][i];
else
sum[i]=dp[29][i];
scanf("%d",&T);
while(T--){
scanf("%lld",&x);
i=get_i(sum,x,MAX);
if(i)
y=x-sum[i-1];
else
y=x;
//printf("i:%d y:%lld\n",i,y);
for(j=29,ans=0;j>=0;j--)
if(j)
for(k=z=0;k<10;k++){
z+=dp[j][i-k*two[j]];
if(z>=y){
y-=z-dp[j][i-k*two[j]];
i-=k*two[j];
ans+=k*ten[j];
//printf("i:%d y:%lld\n",i,y);
break;
}
}
else
ans+=i;
printf("%llu\n",ans);
}
return 0;
}
int get_i(long long*a,long long num,int size){
if(size==0)
return 0;
if(num>med(a,size))
return get_i(&a[(size+1)>>1],num,size>>1)+((size+1)>>1);
else
return get_i(a,num,(size-1)>>1);
}
long long med(long long*a,int size){
return a[(size-1)>>1];
}
Solution in C++ :
In C++ :
#include<bits/stdc++.h>
#include<iostream>
using namespace std;
#define fre freopen("in.txt","r",stdin);freopen("0.out","w",stdout)
#define abs(x) ((x)>0?(x):-(x))
#define MOD 1000000007
#define LL signed long long int
#define scan(x) scanf("%d",&x)
#define print(x) printf("%d\n",x)
#define scanll(x) scanf("%lld",&x)
#define printll(x) printf("%lld\n",x)
#define rep(i,from,to) for(int i=(from);i <= (to); ++i)
#define pii pair<int,int>
LL dp[300000+5][22];
LL sdp[300000+5];
int main(){
int N = 300000;
for(int i=0;i<=9;++i)dp[i][0] = 1;
for(int i=0;i<=N;++i){
for(int j=1;j<=20;++j){
for(int d=0;d<=9;++d){
if((i-d*(1<<j)) >= 0)
dp[i][j] = (dp[i][j] + dp[i-d*(1<<j)][j-1]);
}
}
sdp[i] = sdp[i-1] + dp[i][20];
}
int Q;
cin>>Q;
while(Q--){
LL x;
cin>>x;
if(x==1){cout<<0<<endl;continue;}
int L = 0;
int R = N;
while(L!=R){
int m = ceil((L+R)/2.0);
if(sdp[m] < x)L=m;
else R = m-1;
}
LL val = L+1;
x -= sdp[L];
int pos = 0;
for(int j=20;j>=1;--j){
for(int d = 0;d<=9;++d){
if(x > dp[val-d*(1<<j)][j-1]){
//cout<<j<<' '<<d<<endl;
x -= dp[val-d*(1<<j)][j-1];
}
else{
if(pos or d){
pos = 1;
cout<<d;
val -= d * (1<<j);
}
break;
}
}
}
cout<<val<<endl;
}
}
Solution in Java :
In Java :
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Solution {
public static void main(String[] args) {
int BITS = 19;
int MAX = 1<<BITS;
long[][] dp = new long[BITS][MAX];
for (int i = 0; i < 10; i++)
dp[0][i] = 1;
for (int i = 1; i < BITS; i++) {
int sub = 1<<i;
for (int j = 0; j < MAX; j++) {
for (int k = 0; k <= 9; k++) {
int rem = j-k*sub;
if (rem < 0)
break;
dp[i][j] += dp[i-1][rem];
}
}
}
long sum = 0;
TreeMap<Long, Integer> sums = new TreeMap<Long, Integer>();
sums.put(0l, -1);
for (int i = 0; i < MAX; i++) {
sum += dp[BITS-1][i];
sums.put(sum, i);
}
Scanner sc = new Scanner(System.in);
int q = sc.nextInt();
for (int z = 0; z < q; z++) {
long n = sc.nextLong();
int val = sums.floorEntry(n-1).getValue()+1;
n -= sums.floorEntry(n-1).getKey();
long ans = 0;
for (int i = BITS-1; i > 0; i--) {
int digit = 0;
while (dp[i-1][val] < n) {
n -= dp[i-1][val];
digit++;
val -= (1<<i);
}
ans *= 10;
ans += digit;
}
ans *= 10;
ans += val;
System.out.println(ans);
}
}
}
Solution in Python :
In Python3 :
import math
import os
import random
import re
import sys
import bisect
import array
import timeit
from itertools import repeat
def decbinValue(x):
ans = 0
p2 = 1
while x > 0:
ans += (x % 10) * p2
p2 *= 2
x //= 10
return ans
class Solution:
def __init__(self):
self.nrepr = {0: 1, 1: 1, 2: 2, 3: 2}
self.ndrepr = {(0,0): 1}
#self.initSimple()
self.init()
#self.test()
# self.speedTest()
def numRepr(self, n):
if n in self.nrepr:
return self.nrepr[n]
ans = 0
for i in range(10):
if n-i >= 0 and (n-i)%2 == 0:
ans += self.numRepr((n-i)//2)
self.nrepr[n] = ans
return ans
def numFixR(self, n, d):
if (n,d) in self.ndrepr:
return self.ndrepr[(n,d)]
if d == 0 and n > 0:
return 0
if n > (2**d - 1) * 9:
return 0
ans = 0
for i in range(10):
if n-i >= 0 and (n-i)%2 == 0:
ans += self.numFixR((n-i)//2, d-1)
self.ndrepr[(n,d)] = ans
return ans
def test(self):
print(10**16)
print(self.numRepr(100000))
print(self.numRepr(100))
start = timeit.default_timer()
self.decibinaryNumbers(10**16)
stop = timeit.default_timer()
self.decibinaryNumbers(10**16)
stop2 = timeit.default_timer()
print(self.decibinaryNumbers(10**16))
print('Time 1st: ', stop - start, '2nd:', stop2 - stop)
for d in range(1, 35000):
if str(self.decibinaryNumbersSimple(d)) != self.decibinaryNumbers(d):
print("Yoop", d, self.decibinaryNumbersSimple(d), self.decibinaryNumbers(d))
break
a = array.array('q', [1,10**8,10**15,10**16])
print(a, a.itemsize)
def speedTest(self):
print(10**16)
print(self.numRepr(100000))
print(self.numRepr(100))
start = timeit.default_timer()
self.decibinaryNumbers(10**16)
stop = timeit.default_timer()
self.decibinaryNumbers(10**16)
stop2 = timeit.default_timer()
print(self.decibinaryNumbers(10**16))
print('Time 1st: ', stop - start, '2nd:', stop2 - stop)
t1 = timeit.default_timer()
for x in range(10**15, 10**15 + 10000):
self.decibinaryNumbers(x)
t2 = timeit.default_timer()
print('Time many: ', t2 - t1)
def initSimple(self):
d = {}
val = 0
for n in range(1200111):
if n%10 == 0:
val = decbinValue(n)
else:
val += 1
if val not in d:
d[val] = [n]
else:
d[val].append(n)
self.dbl = []
ls = []
for v in range(100):
self.dbl.extend(sorted(d[v]))
ll = len(d[v])
ls.append((ll, self.numRepr(v)))
print(len(self.dbl))
def decibinaryNumbersSimple(self, x):
if x <= len(self.dbl):
return self.dbl[x-1]
else:
return 0
def init(self):
# tmst1 = timeit.default_timer()
self.MAX_VAL = 285113
# print(self.MAX_VAL, bin(self.MAX_VAL), len(bin(self.MAX_VAL)))
self.MAX_L = 20
# tmst2 = timeit.default_timer()
self.ndra = [list(repeat(0, self.MAX_VAL)) for i in range(self.MAX_L)]
# self.ndra = [array.array('q', repeat(0, self.MAX_VAL)) for i in range(self.MAX_L)]
# self.ndra = [memoryview(self.mem[i*8*self.MAX_VAL: (i+1)*8*self.MAX_VAL]).cast('q') for i in range(self.MAX_L)]
# [array.array('q', repeat(0, self.MAX_VAL)) for i in range(self.MAX_L)]
for d in range(self.MAX_L):
self.ndra[d][0] = 1
# tmst3 = timeit.default_timer()
max_values = [(2**d - 1) * 9 for d in range(self.MAX_L)]
for v in range(1, self.MAX_VAL):
# self.ndra[0][v] = 0 # default is zero
rr = [(v-i)//2 for i in range(10) if v-i >= 0 and (v-i)%2 == 0]
slc = slice(min(rr), max(rr) + 1)
for d in range(1, self.MAX_L):
if v <= max_values[d]:
self.ndra[d][v] = sum(self.ndra[d-1][slc])
# tmst4 = timeit.default_timer()
self.ssum = list(repeat(0, self.MAX_VAL))
self.ssum[0] = self.ndra[-1][0]
for v in range(1, self.MAX_VAL):
self.ssum[v] = self.ssum[v-1] + self.ndra[-1][v]
# print(self.ssum[-1])
# tmst5 = timeit.default_timer()
# print('Time whole: ', tmst4 - tmst1)
# print('Time : ', tmst2 - tmst1)
# print('Time : ', tmst3 - tmst2)
# print('Time : ', tmst4 - tmst3)
# print('Time : ', tmst5 - tmst4)
# for v in range(1, self.MAX_VAL//1000):
# d = 3
# if self.ndra[d][v] != self.numFixR(v, d):
# print("NOOO", v, self.ndra[d][v], self.numFixR(v, d))
# break;
def numFixArr(self, n, d):
return self.ndra[d][n]
def decibinaryNumbers(self, x):
if x == 1:
return "0"
# find decibinary value
v = bisect.bisect_left(self.ssum, x)
x = x - self.ssum[v-1]
# v = 0
# while self.numRepr(v) < x:
# x -= self.numRepr(v)
# v += 1
# if v != newv or x != newx:
# print("WWW", x, newx, v, newv)
# return 0
# find lenth of result
l = 0
while self.ndra[l][v] < x:
l += 1
res = [0] * l
selected_value = 0
rv = v
for pos in range(l):
dig_left = l-pos-1
p2 = 2**dig_left
ndra_dig = self.ndra[dig_left]
for dig in range(10):
ndr = ndra_dig[rv]
if ndr < x:
x -= ndr
else:
res[pos] = dig
break
rv -= p2
return "".join(map(str,res))
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
q = int(input())
sol = Solution()
for q_itr in range(q):
x = int(input())
result = sol.decibinaryNumbers(x)
fptr.write(str(result) + '\n')
fptr.close()
View More Similar Problems
Insert a node at a specific position in a linked list
Given the pointer to the head node of a linked list and an integer to insert at a certain position, create a new node with the given integer as its data attribute, insert this node at the desired position and return the head node. A position of 0 indicates head, a position of 1 indicates one node away from the head and so on. The head pointer given may be null meaning that the initial list is e
View Solution →Delete a Node
Delete the node at a given position in a linked list and return a reference to the head node. The head is at position 0. The list may be empty after you delete the node. In that case, return a null value. Example: list=0->1->2->3 position=2 After removing the node at position 2, list'= 0->1->-3. Function Description: Complete the deleteNode function in the editor below. deleteNo
View Solution →Print in Reverse
Given a pointer to the head of a singly-linked list, print each data value from the reversed list. If the given list is empty, do not print anything. Example head* refers to the linked list with data values 1->2->3->Null Print the following: 3 2 1 Function Description: Complete the reversePrint function in the editor below. reversePrint has the following parameters: Sing
View Solution →Reverse a linked list
Given the pointer to the head node of a linked list, change the next pointers of the nodes so that their order is reversed. The head pointer given may be null meaning that the initial list is empty. Example: head references the list 1->2->3->Null. Manipulate the next pointers of each node in place and return head, now referencing the head of the list 3->2->1->Null. Function Descriptio
View Solution →Compare two linked lists
You’re given the pointer to the head nodes of two linked lists. Compare the data in the nodes of the linked lists to check if they are equal. If all data attributes are equal and the lists are the same length, return 1. Otherwise, return 0. Example: list1=1->2->3->Null list2=1->2->3->4->Null The two lists have equal data attributes for the first 3 nodes. list2 is longer, though, so the lis
View Solution →Merge two sorted linked lists
This challenge is part of a tutorial track by MyCodeSchool Given pointers to the heads of two sorted linked lists, merge them into a single, sorted linked list. Either head pointer may be null meaning that the corresponding list is empty. Example headA refers to 1 -> 3 -> 7 -> NULL headB refers to 1 -> 2 -> NULL The new list is 1 -> 1 -> 2 -> 3 -> 7 -> NULL. Function Description C
View Solution →