Can someone tell me whats wrong with my code
https://www.hackerrank.com/challenges/xor-and-sum/problem
Code
#include <bits/stdc++.h>
using namespace std;
/*
* Complete the 'xorAndSum' function below.
*
* The function is expected to return an INTEGER.
* The function accepts following parameters:
* 1. STRING a
* 2. STRING b
*/
unsigned long long int convert(string s)
{
reverse(s.begin(), s.end());
unsigned long long int ans = 0;
unsigned long long int n = s.length();
unsigned long long int mul =1 ;
for(unsigned long long int i = 0 ; i<n; i++)
{
ans+=mul*(s[i]=='1');
mul*=2;
}
return ans ;
}
unsigned long long int xorAndSum(string a, string b) {
unsigned long long int mod = 1000000007;
unsigned long long int a1 = convert(a);
unsigned long long int b1 = convert(b);
long long int ans =0 ;
for(int i =0 ; i <=314159 ; i++)
{
unsigned long long int bn = (b1<<i)%mod;
ans = (ans + (a1^bn)%mod)%mod;
}
return ans ;
}
int main()
{
ofstream fout(getenv("OUTPUT_PATH"));
string a;
getline(cin, a);
string b;
getline(cin, b);
long long int result = xorAndSum(a, b);
fout << result << "\n";
fout.close();
return 0;
}
You cannot do b1 << 314159, integers can't hold that value
For this questions you cannot use c++ standard int, long long int, or even unsigned long long int because integers in this question can go up to 10^5 bits long. So you must implement it yourself. Store a and b as strings, create an xor function for string representation of binary numbers, and use it on a, b. Next, notice that the summation is just the sum of a geometric sequence. The total sum is equal to ((a xor b)<<314160) — 1. After computing this value (in string representation because int cannot store this value) just compute the mod bit by bit. Sum them up and you have your answer.