您的位置:首页 > 其它

算法学习--整型转字符串

2015-09-23 20:48 302 查看
字符串转整型的逆过程

代码思路:

1、输入一个整型数,判断整型数是否<0;

2、不断地对整型数做取余,得出余数与 ‘ 0 ’ 相加,然后整型除去10,就是说,把整型个十百千每一位都取出来,变成ASCII码的数字,存起来;

3、最后把正负号补上。

代码如下:

#include <string>
#include <iostream>
#include <algorithm>
#include <cassert>
using namespace std;
string intToString( int x )
{
bool isNegative = x < 0;
x = abs( x );

string s;
while( x != 0 )
{
s.push_back( '0' + x % 10 );
x /= 10;
}
if( s.empty() )
{
return "0";
}

if( isNegative )
{
s.push_back( '-' );
}

reverse( s.begin(), s.end() );
return s;
}
int main()
{
int s1 = 2468;
string s2 = "abcd";
string s3 = "1357";
string result = s3 + intToString(s1) + s2;

cout << result << endl;
system("pause");
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息