Interconvert Strings and Integers

EPI 7.1


Description:

Convert between integer and string. Negative value allowed.

Example:

Note

Idea:

Assume valid string of integer.

Code:

#include <iostream>
#include <vector>
#include <string>
#include <algorithm>

using namespace std;

string intToString(int num){
    bool isNegative;
    if(num<0){
        isNegative=true;
    }

    num=abs(num);
    string result;
    do{
        result.push_back('0'+num%10);
        num /= 10;
    }while(num);

    if(isNegative){
        result.push_back('-');
    }
    return string(result.rbegin(), result.rend());
}

int stringToInt(string num){
    int result=0;
    int i=0;
    bool isNegative;
    if(num[0] == '-'){
        i++;
        isNegative=true;
    }
    while(i<num.size()){
        result = result*10 + num[i]-'0';
        i++;
    }
    return isNegative? result*-1: result;
}

int main(){
    cout<<intToString(-1111)<<endl;
    cout<<stringToInt("-1111")<<endl;
}

results matching ""

    No results matching ""