I was solving Quasi-Binary problem (doesn't matter) on Codeforces and this is my submission. This is the code I have produced :
#include <iostream>
#include <cmath>
using namespace std;
int quasi_binary(int num, int tens)
{
int res,digit;
if(num == 0)
{
return 0;
}
digit = num%10;
num = num/10;
res = quasi_binary(num, tens+1);
if(digit)
{
cout << 1;
return ((digit-1)*pow(10,tens)+res);
}
else
{
cout << 0;
return res;
}
}
int main()
{
int n,k=-1,temp,digit;
cin >> n;
//this loop calculates the value of k,as it needs to be printed first
temp=n;
while(temp)
{
digit = temp%10;
temp = temp/10;
if(digit>k)
k=digit;
}
cout << k << endl;
//print those k quasi-numbers
while(n)
{
n = quasi_binary(n,0);
cout << " ";
}
return 0;
}
I don't see any statement that can produce undefined behaviour on different compilers. I used proper brackets at proper places, as well to avoid ambiguity. Still getting undefined behaviour. Can anyone please help to locate the statement/instruction which is generating the undefined behaviour.
Input
415
Output (online judge) - incorrect
5
111 101 101 11 11 11 11 11 11 11 11 11
Output (on my 64-bit PC with gcc) - correct
5
111 101 101 101 1