[프로그래머스] 문자열을 정수로 바꾸기(Kotlin)

0

프로그래머스

목록 보기
71/127
post-thumbnail

[프로그래머스] 문자열을 정수로 바꾸기

풀이(Kotlin)

class Solution {
    fun solution(s: String): Int {
        var answer = 0
        var digit = 1
        
        //s[s.length-1]~s[1]
        for(i in s.length-1 downTo 1){
            val num = s[i].toInt() -'0'.toInt()
            answer += (num * digit) //add to end of array
            digit *= 10
        }
        //s[0]
        if(s[0] == '+') //do nothing
        else if(s[0] == '-') answer *= (-1)
        else { //another num
            val num = s[0].toInt() -'0'.toInt()
            answer += (num * digit) //add to end of array
        }
        return answer
    }
}
profile
Be able to be vulnerable, in search of truth

0개의 댓글