Decimal to binary too slow!

Hi everyone, i made a program that given a decimal natural number it returns its binary, hexadecimal and octal.

The program works but is way too slow. Anyone knows what to improve?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
#include <iostream>
using namespace std;

string to_hexa (int n) {
	if (n != 0) {
		int a = n%16;
		if (a == 0) return to_hexa(n/16) + "0";	
		if (a == 1) return to_hexa(n/16) + "1";	
		if (a == 2) return to_hexa(n/16) + "2";	
		if (a == 3) return to_hexa(n/16) + "3";	
		if (a == 4) return to_hexa(n/16) + "4";	
		if (a == 5) return to_hexa(n/16) + "5";	
		if (a == 6) return to_hexa(n/16) + "6";	
		if (a == 7) return to_hexa(n/16) + "7";	
		if (a == 8) return to_hexa(n/16) + "8";	
		if (a == 9) return to_hexa(n/16) + "9";	
		if (a == 10) return to_hexa(n/16) + "A";	
		if (a == 11) return to_hexa(n/16) + "B";
		if (a == 12) return to_hexa(n/16) + "C";
		if (a == 13) return to_hexa(n/16) + "D";	
		if (a == 14) return to_hexa(n/16) + "E";
		if (a == 15) return to_hexa(n/16) + "F";				
	}
	return "";
}

string to_octal (int n) {
	if (n != 0) {
		int a = n%8;
		if (a == 0) return to_octal(n/8) + "0";	
		if (a == 1) return to_octal(n/8) + "1";	
		if (a == 2) return to_octal(n/8) + "2";	
		if (a == 3) return to_octal(n/8) + "3";	
		if (a == 4) return to_octal(n/8) + "4";	
		if (a == 5) return to_octal(n/8) + "5";	
		if (a == 6) return to_octal(n/8) + "6";	
		if (a == 7) return to_octal(n/8) + "7";	
		return to_octal(n/8) + "8";	
	}
	return "";
}


string to_binary (int n) {
	if (n != 0) {
		if (n%2 != 0) return to_binary(n/2) + "1";
		return to_binary(n/2) + "0";		
	}
	return "";
	
}

int main () {
	int n;
	while (cin >> n) {
		if (n == 0) cout << "0 = 0, 0, 0" << endl;
		else cout << n << " = " << to_binary(n) << ", " << to_octal(n) << ", " << to_hexa(n) << endl;
	}
}
Works fine for me. Try more compact:

1
2
3
4
5
6
7
8
string to_hexa (int n) {
        string digit("0123456789ABCDEF");
	if (n != 0) {
		int a = n%16;
		return to_hexa(n/16) + digit[a];					
	}
	return "";
}
Thanks for the reply!

I have another question :D

Is there a way to check if a determinate position in a string exists?
So you want to check if say, position 64 in a string exists? You could just get the size of the string and if the size is < x, then that position will not exist. If you want to then check what is actually held at that position, you can use at(x).
1
2
3
4
std::string s; 
s = "this is a string"
std::cout << s.size(); 
std::cout << s.at(7); 
And is it possible to erase some string position?

Like when i have already read a number, i want to erase it and make the string size lower one number too.
Topic archived. No new replies allowed.