I don't think you need the power (or pow) in your code? Also, giblit's suggestion does make sense! If you alter line 4 accordingly, your code will work.
vlad's solution is the standard one -- add to back of string and then swap at the end -- but your add-to-the-front approach should produce the same result.
Note that the reserve is an optimization, to speed up operator++; the conversion code will work fine if it is omitted. If it is used, then you can remove the space capacity using binary.shrink_to_fit();
if you're using C++11 or [code]string(binary).swap(binary);
.
Personally I would use
reverse( binary.begin(), binary.end() );
(the std::reverse algorithm) rather than
binary.assign( binary.rbegin(), binary.rend() );
As your code stands, it's line 4 which is very sick:
binary = (remainder * pow(10.0, i)) + "" + binary;
Breaking it down...
-
pow(10.0, i)
- returns a double [1]
Note that passing an int for the first parameter of pow() can confuse the compiler as there is more than one overload of pow(). But they do all return some sort of floating point number: float, double, long double.
-
remainder *
{value} - returns another double (int values are promoted to doubles before performing multiplication with a double.)
- {value}
+ ""
- is invalid for a double value.
It's also invalid for an int value, so casting to an int would be a waste of time.
In this situation, "" is seen as the memory address of a blank string. And you can't add a memory address to an int. You can, however, add the value of the address:
1 2
|
int i = 0;
int j = i + (int)"";
|
or add an integer to an address; this is part of pointer arithmatic (see Pointer craft
http://www.cplusplus.com/articles/z186b7Xj/ )
1 2
|
const char* p = "Hello world" + 6;
cout << p << endl; // outputs "world"
|
But there is a std::string overload of operator= which knows how to add a C null-terminated string to a C++ string. So you if you convert (not cast) the required value to a string, then you can add it on.
To convert a double or int to string you need to use an ostringstream (there are other ways, but this is the prefered method in C++ code.)
So, bearing all of this in mind, you could "fix" your code like this:
1 2 3 4 5 6 7 8 9 10
|
string binary = "";
for (int i = 0; input != 0; i++) {
int remainder = input%2;
//binary = (remainder * power(10, i)) + "" + binary;
int j = (remainder * power(10, i)) + (int)"";
ostringstream oss; // needs <sstream>
oss << j;
binary = oss.str() + binary;
input = input/2;
}
|
But the o/p value of this code for 64 is:
5329930432993043299304329930432993043299304329930 |
rather than the required
Andy