본문 바로가기

ALGORITHM/c&c++ leetcode

[c && swift/LeetCode] Reverse Integer

1. c version

4ms/ 5.5MB

왜 이렇게 오래 걸린거지

 

int reverse(int x){
    long temp = 0;
    long value = x;

    if (x < 0)
    {
        value = value * -1;
    }
    while(value)
    {
        temp = temp * 10 + (value % 10);
        value = value / 10;
    }
    if (x < 0)
    {
        temp = temp * -1;
    }
    if (temp > 2147483647 || temp < -2147483648)
        return 0;
    return temp;
}

 

 

 

2. swift version

swift는 long type이 그냥 Int이기 때문에 c보다 오버플로우 언더플로우에 유연하긴 함

c에서의 자료형 swift 에서의 자료형
signed char  Int8
short Int16
int Int32
long Int
long long Int64

 

4ms / 16.5MB 

? 메모리 왜 이렇지

 

class Solution {
    func reverse(_ x: Int) -> Int {
        var temp: Int = 0;
        var value: Int = x;
        if (x < 0)
        {
            value = value * -1;
        }
        while (value != 0)
        {
            temp = temp * 10 + (value % 10);
            value = value / 10;
        }
        if (x < 0)
        {
            temp = temp * -1;
        }
        if (temp > 2147483647 || temp < -2147483648)
        {
            return 0;
        }
        return temp;
    }
}

난이도는 medium이지만 체감은 easy of easy..

맨날 42서울에서 하던거라 그런가? 아니 그냥 문제 자체도 쉬운듯

'ALGORITHM > c&c++ leetcode' 카테고리의 다른 글

[C/LeetCode] Arithmetic Slices  (0) 2022.03.03
[c/LeetCode] Single Number  (0) 2022.02.15
[c/LeetCode] Median of Two Sorted Arrays  (0) 2022.02.12
[c/LeetCode] Add Two Numbers  (0) 2022.02.11
[c/LeetCode] Two Sum  (0) 2022.02.10