Блог пользователя basantCoder

Автор basantCoder, история, 5 лет назад, По-английски

You start with 0 and you have to Find the minimum number of operations to reach 'n'. In one operation you can add or subtract any 2^k to your current number. Where k can be any positive integer.
Constraints:
test cases <200,000;
1 <= | n | <= 1,000,000,000 . Example:
INPUT:
First line is no. of test cases, then a single integer 'n' on each line.
5
1
2
0
6
10
OUTPUT:
1
1
0
2
2
Can anybody help??

  • Проголосовать: нравится
  • -25
  • Проголосовать: не нравится

»
5 лет назад, скрыть # |
 
Проголосовать: нравится 0 Проголосовать: не нравится

Auto comment: topic has been updated by basantCoder (previous revision, new revision, compare).

»
5 лет назад, скрыть # |
← Rev. 4  
Проголосовать: нравится 0 Проголосовать: не нравится

Why not try to reach from n to 0 by subtracting nearest power of 2(floor)

long long n,ans=0;
cin>>n;
while(n>0){
    n = n - pow(2,(int)__lg(n));
    ans++;
}
cout<<ans<<'\n';

Maybe Like this...Hope its not live Rn

»
5 лет назад, скрыть # |
 
Проголосовать: нравится 0 Проголосовать: не нравится

As any n can be represented in binary form which is nothing but sum of powers of 2. So the answer will be number of 1s in binary notation of n. Example: $$$10 = (1010)_2$$$ Here count of 1s = 2 = answer

»
5 лет назад, скрыть # |
← Rev. 4  
Проголосовать: нравится 0 Проголосовать: не нравится

int recur(n){ if(n == 0) return 0; else if((n & (n - 1)) == 0) return 1; int temp 1e9; for(int i = 0; i <= 14; i++){ int val = abs(n - (1 << i)); temp = min(temp, 1 + recur(val)); } return temp; } void solve() { ll n; cin >> n; n = abs(n); cout << recur(n); }

to reduce time complexity you can do memoization

»
5 лет назад, скрыть # |
 
Проголосовать: нравится 0 Проголосовать: не нравится

Let, f(x) = Number of set bit's in binary representation of x. Answer will be min(f(x), f(-x)).

»
5 лет назад, скрыть # |
 
Проголосовать: нравится 0 Проголосовать: не нравится

Had a hard time reading the title