-
[LeetCode]Reverse IntegerAlgo 2019. 6. 22. 15:26
-
문제
문자 스트링을 정수로 변환하는 atoi(), itoa()와 관련된 문제이다.
-
Solution
나의 코드는 아래와 같다.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersfun reverse5(x : Int) : Int { return try { if (x > 0) x.toString().reversed().toInt() else -Math.abs(x).toString().reversed().toInt() } catch (e: java.lang.NumberFormatException) { 0 } } -
Result
atoi()란 문자 스트링을 정수 값으로 변환하는 것을 의미한다.
c에서는 stl로 stdlib.h 파일에 선언되어있다고 한다.그래서 해당 문제의 discussion을 가보면 뭐 여타 다른 이유로 있겠지만 압도적으로 c로 푼 코드가 퍼포먼스가 좋다.
Kotlin으로 해당 문제를 풀어본 필자는 String.reversed()가 가장 먼저 떠올랐다.
그렇지만 NumberFormatException이 발생해서 애좀 썼다...여차저차 해서 풀었는데 발생했던 오류 중 하나는 ( - )이다.
x를 바로 String.reverse()했더니 -까지 뒤에 붙어 버려서
초반에 x의 양수 음수로 분기 처리를 하였다.
그 후에 Math.abs(x)로 절댓값으로 앞에 -를 붙여줘서 이쁘게 나타내어 주었다.
또 다르게 발생했던 NumberFormatException이다.
try {} cath() 문을 사용해서 해결하였다.(이것은 다른 풀이법을 참고하였음)
NubmerFormatException이 발생한 이유는 문자형 > 숫자형으로 바뀔 때 발생한다고 한다.
Kotlin에서 toInt를 이용하여 String을 Int로 바꿔줄 때 사용하는
Kotlin toInt로가면 발생할 수 있는 예외 상황에 대하여 명시되어있다.NumberForatException에 대하여 자세하게 알고 싶다면 밑에 참고 Ref에 관련된 내용을 정리해 놓은 블로그를 작성해 놓겠다.
Reverse Integer - LeetCode
Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.
leetcode.com
toInt - Kotlin Programming Language
kotlinlang.org
- NumberFormatException : https://alvinalexander.com/blog/post/java/java-faq-what-is-numberformatexception
What is a Java NumberFormatException? | alvinalexander.com
Java exception FAQ: What is a Java NumberFormatException? Answer: A Java NumberFormatException usually occurs when you try to do something like convert a String to a numeric value, like an int, float, double, long, etc. NumberFormatException example The be
alvinalexander.com
LIST'Algo' 카테고리의 다른 글
[LeetCode]Jewels and Stones (0) 2019.07.06 [LeetCode]Palindrome Number (0) 2019.06.30 [LeetCode] Climbing Stairs (0) 2019.05.06 [BOJ-2566]백준 알고리즘 2566 [Kotlin][Java] (0) 2019.04.28 [LeetCode] Two sum (0) 2019.03.10 -