Here is a scaffold for a C++ solution, that doesn't solve the problem, but throws you some linguistic tinker-toys you'd need for a fairly straightforward implementation. It iterates backward through the digits and builds up a result which just has 1s where both numbers have nonzero digits, and 0s otherwise:
#include <string>
#include <iostream>
using namespace std;
// For a more circumspect treatment of the digit/char conversion, read up:
// http://stackoverflow.com/questions/439573/how-to-convert-a-single-char-into-an-int
char charFromDigit(int d) {
return d + '0';
}
int digitFromChar(char c) {
return c - '0';
}
// all this routine does is iterate backward through the digits of both
// numbers and build up a result which has a 1 digit if both numbers are
// non-zero for that place value, and a 0 digit if they're both 0
string get_something(const string& a, const string& b) {
// get reverse ("r"begin) iterators so we can index backwards
// across the two strings. This way we look at the last digits
// first
string::const_reverse_iterator a_iterator = a.rbegin();
string::const_reverse_iterator b_iterator = b.rbegin();
// this variable holds the result that we build
string result;
// simple loop that just prints digits as long as the iterators
// haven't indicated we're out of characters by reaching their
// respective "r"ends...
while (a_iterator != a.rend() || b_iterator != b.rend()) {
int a_digit = 0;
if (a_iterator != a.rend()) {
a_digit = digitFromChar(*a_iterator);
a_iterator++;
}
int b_digit = 0;
if (b_iterator != b.rend()) {
b_digit = digitFromChar(*b_iterator);
b_iterator++;
}
cout << "A digit " << a_digit << ", B digit " << b_digit << endl;
int out_digit = 0;
if ((a_digit != 0) && (b_digit !=0))
out_digit = 1;
result.insert(result.begin(), charFromDigit(out_digit));
}
return result;
}
int main(int argc, char* argv[]) {
string a ("1000000000001");
string b ("0100000000001");
cout << "A is " << a << endl;
cout << "B is " << b << endl;
cout << "Return Value = " << get_something(a, b) << endl;
return 0;
}
The output of the program is:
A is 1000000000001
B is 0100000000001
A digit 1, B digit 1
A digit 0, B digit 0
A digit 0, B digit 0
A digit 0, B digit 0
A digit 0, B digit 0
A digit 0, B digit 0
A digit 0, B digit 0
A digit 0, B digit 0
A digit 0, B digit 0
A digit 0, B digit 0
A digit 0, B digit 0
A digit 0, B digit 1
A digit 1, B digit 0
Return Value = 0000000000001
Really it makes a big difference, if you're in a class, if you're solving it in the framework they're teaching you about. If everything you're learning is char*
and strlen()
and such, you're learning C... not idiomatic C++. In C++ you have a lot more automatic management of memory and an encouragement to use more generic algorithmic approaches.