Recursion also works.Obviously time taken is more.
#include <bits/stdc++.h>
using namespace std;
vector<unsigned long long int> ans;
void func(unsigned long long int x)
{
unsigned long long int lgvalue,finalvalue;
if(x == 1)
{
ans.push_back(1);
return;
}
else if(x==0)
{
return;
}
lgvalue = (unsigned long long int)log2(x)+1;
finalvalue = (unsigned long long int)powl(2,lgvalue)-1;
ans.push_back(finalvalue);
return func(finalvalue-x);
}
void solve()
{
ans.clear();
unsigned long long int c;
cin>>c;
if(c == 0)
{cout<<2<<endl<<"1 1"<<endl;
return;}
func(c);
cout<<(unsigned long long int)ans.size()<<endl;
reverse(ans.begin(),ans.end());
for(int i =0;i<ans.size();i++ )
{
cout<<ans[i]<<" ";
}
cout<<endl;
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int t;
cin>>t;
while(t--)
{
solve();
}
}
I have a slightly different approach that may be more intuitive. My Code
Convert C to binary.
Eg: 25 = 11001
Now, since numbers in array can only have set bits in binary form,
Therefore, for 11001 Ans= 11111 00111 00001
Conclusion:
At positions with set bit, number of set bits in the final answers array is odd
Algorithm:
Iterate from left to right and create a non-decreasing array
In this case: 11001 → 11223 How? At places with set bits in C, number of set bits should be odd and at unset bits, it should be even.
Now, from 11223, you can very easily generate the binary numbers that are part of the final array.
Eg: After11111, Remaining → 00112 After00111, Remaining → 00001 After00001, Remaining → 00000
Implementationsuggestion:
Using bitset will make work with binary numbers much easier
#include <bits/stdc++.h>
using namespace std;
string binary(long long n)
{
string s = "";
if (n == 0)
{
s += '0';
return s;
}
while (n > 0)
{
long long k = n % 2;
s += to_string(k);
n = n / 2;
// cout << k << s[i] << endl;
}
// s[i] = '\0';
// reverse(s.begin(), s.end());
return s;
}
int main()
{
int t;
cin >> t;
while (t--)
{
long long n;
cin >> n;
string str = binary(n);
// cout << str << endl;
vector<long long> v;
if (str.size() == 1 and str[0] == '0')
{
v.push_back(1);
v.push_back(1);
}
else
{
int f = 1;
for (int i = str.size() - 1; i >= 0; i--)
{
char k = f + '0';
if (str[i] == k)
{
long long y = (long long int)pow(2, i + 1) - 1;
v.push_back(y);
f = 1 - f;
}
}
}
cout << v.size() << endl;
for (int i = 0; i < v.size(); i++)
{
cout << v[i] << " ";
}
cout << endl;
}
return 0;
}
can anyone help me with my code ,
I found a pattern , and it works for each case , cant find anyone that fails .
Please help . Here is code #include <bits/stdc++.h>
using namespace std; #define ll long long
int main() {
// your code goes here
ll t;
cin>>t;
while(t–)
{
ll c;
cin>>c;
ll twos = 2;
ll temp = twos-1;