iT邦幫忙

2021 iThome 鐵人賽

DAY 26
0
AI & Data

想到甚麼打甚麼系列 第 26

找LeetCode上簡單的題目來撐過30天啦(DAY26)

題號:7 標題;Reverse Integer 難度:Medium

Given a signed 32-bit integer x, return x with its digits reversed. If reversing x causes the value to go outside the signed 32-bit integer range [-231, 231 - 1], then return 0.
Assume the environment does not allow you to store 64-bit integers (signed or unsigned).

Example 1:
Input: x = 123
Output: 321
Example 2:
Input: x = -123
Output: -321
Example 3:
Input: x = 120
Output: 21
Example 4:
Input: x = 0
Output: 0

Constraints:
• -231 <= x <= 231 - 1

我的程式碼

#include <stdio.h>  
#include <stdlib.h>  
#include <string.h>

int reverse(int x){

    if(x == 0)
        return  0;

    if(x<0&&x<=-2147483648)
        return  0;
    int i,j=0,num=x;
    
    if(x<0){
        x = -(x);
        j = -1;
    }
    int n = log10(x) + 1;

    //printf("%d\n",n);
    char *temp = calloc(n, sizeof(char));
    char *result = calloc(n, sizeof(char));
    for (i = n-1; i >= 0; --i, num /= 10)
    {
        temp[i] = (num % 10) + '0';
        //printf("%c",temp[i]);
    }
    //printf("%d\n",n);

    for(i=0;i<n;i++){
        result[n-1-i] = temp[i];
    }
    x=0;
    long y=0,num2=1;
    
    for (i = 0; i < n; i++, num2*= 10)
    {   
        y = y + (result[n-i-1]-48) *num2;
        printf("xxx:%d",y);
    }
    if(y>0&&y>=2147483647)
        return  0;
    if(y<0&&y<=-2147483648)
        return  0;
    return y;

}

DAY26心得
今天早早寫出來,可以早早睡覺了呢~


上一篇
找LeetCode上簡單的題目來撐過30天啦(DAY25)今天國慶放假啦
下一篇
找LeetCode上簡單的題目來撐過30天啦(DAY27)
系列文
想到甚麼打甚麼30

尚未有邦友留言

立即登入留言