中国国家话剧院难进吗:用非递归将一个整数n转换成一个字符串。如将1234转换为"1234"。

来源:百度文库 编辑:查人人中国名人网 时间:2024/04/30 03:11:42
用C++编写的程序代码 帮忙传一份

 
 
 
如果你“非递归”的意思是循环,参考 iToStr1( )。
如果凡非递归都可以,参考简便的 iToStr2( )。

#include <iostream>
#include <string>
#include <sstream>
using namespace std;

string iToStr1( int i ) {
    bool negative = i < 0 ? i = -i : false;
    string s;
    do {
        s.insert( 0u, 1, i % 10 + '0' );
    } while( i /= 10 );

    if( negative ) s = '-' + s;

    return s;
}

string iToStr2( int i ) {
    stringstream ss;
    ss << i;

    return ss.str( );
}

int main( ) {

    int n = 1234;

    cout << iToStr1( n ) << endl
         << iToStr2( n ) << endl;

    return 0;
}