#include <iostream>
#include <algorithm>
std::string itos(int i, int base)
{
std::string str;
unsignedint ui = i;
/* If i is negative and base is 10; then we put the sign in str */
if (i < 0 && base == 10) {
str += '-';
ui = -i;
}
/* Now convert ui into a the base base and store the result in str */
do {
int rem = ui % base;
str += (rem < 10) ? rem + '0' : rem + 'a' - 10;
} while (ui /= base);
/* Reverse the string: */
std::reverse(str.begin(), str.end());
return str;
}
int main() {
int n = 0,
base = 0;
std::cout << "Enter a number and the base to convert it into\n"
<< "Number: ";
std::cin >> n;
std::cout << "Base: ";
std::cin >> base;
std::cout << "Decimal " << n << " is " << itos(n, base)
<< " in base " << base << std::endl;
return 0;
}
Enter a number and the base to convert it into
Number: 15
Base: 2
Decimal 15 is 1111 in base 2
No, base 1 can't exist. What happens in the do-while loop if you call itos(16, 1)?
Hint: infinite loop
Edit: also, have you not noticed the pattern of numeric bases? The largest digit for base 10 is 9, or 10 - 1. The largest digit for base 6 is 5, or 6 - 1. So the highest digit for base 1 would be 0, or 1 - 1. Another reason why base 1 can't exist: it only has 1 digit, 0.