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

字符串转整型的逆过程

代码思路:

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;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值