Home | Projects | Notes > Problem Solving > EPI - 7.1. Interconvert Strings and Integers
Negative numbers are handled by recording the sign and negating the result.
Complexity Analysis:
In practice, int32_t
, int64_t
). But if arbitrary precision number types are used (which some languages, like Python, use by default) then there is no limit to the number of digits (other than available memory obviously).
Solution:
231
2
3using namespace std;
4
5string IntToString(int x)
6{
7 bool is_negative = x < 0 ? true : false;
8 string result;
9
10 if (is_negative)
11 x = -x;
12
13 while (x)
14 {
15 result.insert(0, 1, (x % 10) + '0');
16 x /= 10;
17 }
18
19 if (is_negative)
20 result.insert(0, 1, '-');
21
22 return result;
23}
Inserting a single character rather than a string:
iterator insert(const_iterator p, char c);
31string s = "bc";
2string::iterator it = s.begin();
3s.insert(it, 'a'); // Insert 'a' to the position pointed to by the iterator 'it'
Inserting n consecutive copies of character
c
:
string& insert(size_t pos, size_t n, char c);
21string s = "bc";
2s.insert(0, 1, 'a'); // Insert 'a' to the position s.at(0) or s[0]
Instead of prepending digits to the string, you could apend them and reverse the string at the end using the
reverse()
algorithm.2412
3using namespace std;
4
5string IntToString(int x)
6{
7bool is_negative = x < 0 ? true : false;
8string result;
9
10if (is_negative)
11x = -x;
12
13while (x)
14{
15result += x % 10 + '0';
16x /= 10;
17}
18
19if (is_negative)
20result += '-'; // Add the negative sign back
21
22reverse(result.begin(), result.begin());
23return result;
24}
Negative numbers are handled by recording the sign and negating the result.
Complexity Analysis:
Solution:
171
2
3using namespace std;
4
5int StringToInt(string& s)
6{
7 bool is_negative = s.at(0) == '-';
8 int result = 0;
9
10 for (int i = is_negative ? 1 : 0; i < s.size(); i++)
11 {
12 int digit = s.at(i) - '0';
13 result = result * 10 + digit;
14 }
15
16 return is_negative ? -result : result;
17}