try:
for i in range(int(input())):
p = int(input())
n = p
menu = 0
rem = 0
stri = ''
while n > 0:
rem = n % 2
stri = stri + str(rem)
n = n - rem
n = n // 2
stri = stri[::-1]
if p in range(1,2049):
for j in stri:
menu += int(j)
print(menu)
else:
for j in stri:
menu += int(j)
if menu == 1:
print(p//2048)
else:
print(menu)
except: pass
Check This Out.
Menu Element Is denoted By (2**x) where x ranges from 0-11(inclusive).
My Approach:
- Create a list menu. where each element is 2**x and x ranges from 0-11 inclusive.
- start a reverse loop to find the greatest element which is smaller than p.
- p = p % element found in the previous step
- increase counter (Answer) by p // element
- Also add a break statement incase p reaches 0
CODE:
menu = [2**x for x in range(12)]
T = int(input())
for tc in range(T):
p = int(input())
ans = 0
for item in range(11, -1, -1):
if p == 0: break
if p >= menu[item]:
ans += p // menu[item]
p = p % menu[item]
print(ans)
Approach is
Take all prices in an array in decreasing order.
ar[12]={2048,1024,…,1}
price=k;
int ans=0,i=0;
while(price>0)
{
ans+=(price/ar[i]);
price%=ar[i];
i++;
}
print ans ;
2 Likes