鱼C论坛

 找回密码
 立即注册
查看: 2085|回复: 0

[技术交流] 【朱迪的LeetCode刷题笔记】7. Reverse Integer #Easy #C

[复制链接]
发表于 2021-3-18 07:17:46 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
7. Reverse Integer #Easy

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
C
#include <limits.h>
#include <stdbool.h>

int reverse(int x){
    int n = 0;
    int r = 0;
    
    bool is_negative = false;
    if (x < 0) {
        is_negative = true;
    }
    if (x == INT_MIN) {
        return 0;
    } 
    int y = abs(x);
    while (y >= 0) {
        r = y % 10;
        if ((y / 10)== 0) {
           if (n > (INT_MAX / 10)) {
               return 0;
           } else if ((n == (INT_MAX / 10)) && is_negative && (r > ((INT_MAX % 10) + 1))) {
               return 0;
           } else if ((n == (INT_MAX / 10)) && !is_negative && (r > (INT_MAX % 10))) {
               return 0;
           } else {
               n = (n * 10) + r;
               if (is_negative) {
                   return (n * -1);
               } else {
                   return n;
               }
           }
        } else {
            n = (n * 10) + r;
            y = y / 10;
        }
    }  
    return -1;
}
WeChat Image_20210317191616.png

!!!good style -> always return sth.
!!!special case -> INT_MIN
!!!negative sign -> bool is_negative
!!!integer overflow -> check before reversing ur last digit

本帖被以下淘专辑推荐:

想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2024-9-22 04:20

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表