Gidhub BE Developer

[Programmers] 문자열을 정수로 바꾸기

2018-07-23
goodGid

Problem

Problem URL : 문자열을 정수로 바꾸기


[1] Answer Code (18. 07. 23)

int solution(string s) {
    int answer = 0;
    int flag = 1;
    if(s[0] == '+' ){
        flag = 1;
        s = s.substr(1,s.length());
    }
    else if ( s[0] == '-'){
        flag = -1;
        s = s.substr(1,s.length());
    }
    
    
    int ans = stoi(s.c_str());
    answer = ans * flag;
    
    return answer;
}


// [2]
#include <sstream>
int solution(string s) {
    int answer = 0;
    stringstream ss;
    ss.str(s);
    ss >> answer;

    return answer;
}


//[3]
int solution(string s) {
    int answer = 0;
    int m = 1;
    for(int i = 0; i < s.size();i++)
    {
        if(s[i] >= '0' && s[i] <= '9')
        {
        answer *= 10;
        answer += (s[i] - 48);
        }
        else if(s[i] == '-')
            m = -1;
    }
    return answer*m;
}



[1] Answer Code (18. 07. 23)

  • String to Int 여러가지 방법 !

Recommend

Index