Unexpected results converting decimal number to binary - c++

# include <iostream>
# include <cmath>
using namespace std;
int main()
{
int p;
int n;
int q;
cin>>n;
int r;
r=0;
for (int i=0,n; n>1; i=i+1,n=n/2)
{
p=n%2;
q= p*(pow(10,i));
r=r + q;
}
cout<<r;
system("pause");
return 0;
}
I am not supposed to use arrays. It compiles fine but when executed and a number is entered, it doesn't produce the desired results.
For instance, when 22 is entered, it gives -2147483648 whereas the desired output would be 10110.

your way is limited and not effient in converting to binary
you should use string it's more helpful and the range is big enough for any number
this is my code for decimal-to-binary
#include<iostream>
#include<string>
#include<stack>
using namespace std;
int main()
{
long long n;
string s,bin;
stack<string> res;
cin>>n;
while(n>0)
{
if(n%2==0)
s='0';
else
s='1';
res.push(s);
n=n/2;
}
while(!res.empty())
{
bin=bin+res.top();
res.pop();
}
cout<<bin<<endl;
return 0;
}
I hope it will help you.

int i=0,n;
should be
int i=0;
I don't know what you thought you were doing there, but what you are actually doing is declaring another variable n. Because the second n variable doesn't have a value the rest of the code doesn't work.
That's not the only problem with your code, but I'm sure you can figure out the rest.

Related

How can I make code more time-efficient that calculates 1's in binary representation of int?

I wrote this code for a problem that asks me to calculate the number of 1's in a binary representation of an integer number, and then find the next number which has the same exact number of 1's in its binary number.
I wrote code and it seemed to work just fine until the OJ gives an error:
time limit exceeded error.
I'd like some idea about how I could avoid this error.
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int binary(int num){
int count=0;
vector <int> vec;
while(num!=0){
int rem=num%2;
num/=2;
vec.push_back(rem);
}
reverse(vec.begin(),vec.end());
for(int i=0;i<vec.size();i++){
if(vec[i]==1){
count++;
}
}
return count;
}
int main()
{
int looper,order=1;
cin>>looper;
while(looper--){
int num;
cin>>num;
int x=binary(num);
int next_num=num+1;
while(binary(next_num)!=x){
next_num++;
}
cout<<"Case "<<order<<": "<<next_num<<endl;
order++;
}
return 0;
}
This:
int next_num=num+1;
while(binary(next_num)!=x){
next_num++;
}
Is extremely inefficient. Consider your number is
1010101.....01111
Then the next bigger number with same number of 1s is
1010101.....11110
I'll leave it to you to realize the general pattern, the point is just that you dont need a loop to convert all numbers to binary and count the 1s. Instead you can directly construct the number in binary.
PS: std::bitset can come in handy when you need to get the binary representation.
You don't need to count 1's if you're just finding next number that has same numbers of 1's
You just need to swap 1 & 0 from right to left for once.
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int binary(int num){
int count=0;
vector <int> vec;
while(num!=0){
int rem=num%2;
num/=2;
vec.push_back(rem);
}
reverse(vec.begin(),vec.end());
for(int i=0;i<vec.size();i++){
while(vec[0]!=vec[i]){
swap(vec[0],vec[i]);
}
// convert binary to decimal
// count = decimal number
return count;
}
int main()
{
int looper,order=1;
cin>>looper;
while(looper--){
int num;
cin>>num;
int x=binary(num);
cout<<"Case "<<order<<": "<<x<<endl;
order++;
}
return 0;
}

Loops not executing in functions C++

Here's my code. Whenever I run the program, I expect that the cout statement in the for loop in the function Binary() to execute. But whenever I input something, it gives me 0
#include<iostream>
#include<math.h>
using namespace std;
long int Binary(int x){
int temp=0,res=0;
for(int i=x;i<0;i--){
temp++;
res=res+ pow(10,temp)*(i%2);
i=i/2;
cout<<i<<" "<<res<<endl;
}
return res;
}
int main(){
int x; cin>>x;
cout<<endl<<Binary(x);
return 0;
}
I think the condition in your for loop is the opposite way round than your expect it. You seem to want it to continue looping until i<0. But it will actually loop while i<0. The condition is already not true when you enter the loop, so it will finish immediately without doing any iterations.
You just have to change the loop i check.
#include<iostream>
#include<math.h>
using namespace std;
long int Binary(int x){
int temp=0,res=0;
for(int i=x;i>0;i--){
temp++;
res=res+ pow(10,temp)*(i%2);
i=i/2;
cout<<i<<" "<<res<<endl;
}
return res;
}
int main(){
int x; cin>>x;
cout<<endl<<Binary(x);
return 0;
}
Check the live version here http://cpp.sh/95z74

Why this code doesn't allow me to receive the whole array?

#include <bits/stdc++.h>
using namespace std;
string bin(int n){
string x="";
while(n!=0)
{
int z=n%2;
x+=to_string(z);
n%=2;
}
return x;
}
int main(){
int t;
cin>>t;
while(t--)
{
int n;
cin>>n;
int a[n];
for(int i=0;i<n;i++)
{
cin>>a[i];
string x=bin(a[i]);
int u=x.size();
int cnt=0;
for(int g=0;g<u;g++)
{
if(x[g]=='1')
++cnt;
}
cout<<cnt<<' ';
}
cout<<'\n';
}
}
This code is given several test cases and each test case will have an array of n integers, for each element in the array I should count the number of ones in the binary representation of it. I wrote a function that expects an integer and returns a string containing the binary representation of it. But I wonder why my code does not end, and not allowing me to receive other numbers in array.
For instance, there's one test case and and only array of 2 integers if I inputted 1 and wait for ever to enter the second number, what's happening?
This is your bin function reduced to the bare minimum:
string bin(int n){
while(n!=0)
{
n%=2;
}
return {};
}
If n is even you will set it to 0 on the first iteration, otherwise you set it to 1 and never change it afterwards (1%2==1). Hence you have a endless loop. I won't spoil you the "fun" of completing the exercise, so I will just point you to using a debugger. If you step trough your code line by line you could have observed how n never changes and why the loop wont stop.
PS: (spoiler-alert) you might want to take a look at std::bitset (end of spoiler)

Why is my Sliding Window algorithm not providing correct answers?

The problem is from a recent competition on Codechef.
According to the problem, for a given array of length N, find the maximum average of the numbers of any contiguous sub-array of length between A and B.
Now here is the logic that I have used. I have in a loop iterated over the possible contiguous sub-array length K from A to B. Then for every such K, I have used the sliding window mechanism to find the maximum sum of contiguous
elements of the array. Then I check if the already stored answer (the average) is smaller than the current maximum/K and update the answer.
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
int t;
cin>>t;
while(t--)
{
int n,b,a;
cin>>n>>b>>a;
long long arr[n+1];
for(int i=1;i<=n;i++)
{
cin>>arr[i];
}
double ans=0;
for(int k=a;k<=b;k++)
{
long long maxi=0;
for(int i=1;i<=k;i++)
{
maxi=maxi+arr[i];
}
long long l=maxi;
for(int i=k+1;i<=n;i++)
{
l=l+arr[i]-arr[i-k];
maxi=max(maxi,l);
}
double x=(double)(((double)(maxi))/(double)(k));
ans=max(ans,x);
}
cout<<ans<<endl;
}
}
However, after implementing my logic over as shown, I am getting wrong answers even though I do not know how different they are the actual answer since I have not obtained anything wrong in my processes of debugging.
The following is an edit:
Are my previous code and the following the same?
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
int t;
cin>>t;
while(t--)
{
int n,b,a;
cin>>n>>b>>a;
long long arr[n+1];
for(int i=1;i<=n;i++)
{
cin>>arr[i];
}
long double ans=0;
for(int k=a;k<=b;k++)
{
long long l=0;
for(int i=1;i<=k;i++)
{
l=l+arr[i];
}
ans=max(ans,(long double)(((long double)(l))/(long double)(k)));
for(int i=k+1;i<=n;i++)
{
l=l+arr[i]-arr[i-k];
ans=max(ans,(long double)(((long double)(l))/(long double)(k)));
}
}
cout<<ans<<endl;
}
}
Thanks for helping guys. I tried out the following and it sort of works:
cout<<fixed<<setprecision(10);
setprecision(10)

Pronic number in c++ error

#include<iostream>
using namespace std;
int main(){
int n,i=0,j=1;
cin>>n;
int m;
while(m!=n){
m=i*j;
cout<<m;
i++;
j++;
}
return 0;
}
I want to display Pronic Number ie . 0,2,6,12,20,30,42... When I insert value of n as Pronic Number Code run fine ... and desire output is given.. Bug is when you insert value of n=15 while loop goes to infinity but i want to display till 15 or less than
15.. Here 15 is not a Pronic Number..
Initialize m before using it, plus change your condition to stop the loop when m>n
#include<iostream>
using namespace std;
int main(){
int n,i=0,j=1;
cin>>n;
int m=0;
while(m<=n){
cout<<m<<" ";
i++;
j++;
m=i*j;
}
return 0;
}