鱼C论坛

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

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

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

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

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

x
  1. 7. Reverse Integer #Easy

  2. 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.

  3. Assume the environment does not allow you to store 64-bit integers (signed or unsigned).


  4. Example 1:

  5. Input: x = 123
  6. Output: 321

  7. Example 2:

  8. Input: x = -123
  9. Output: -321

  10. Example 3:

  11. Input: x = 120
  12. Output: 21

  13. Example 4:

  14. Input: x = 0
  15. Output: 0


  16. Constraints:

  17. -231 <= x <= 231 - 1
复制代码

C

  1. #include <limits.h>
  2. #include <stdbool.h>

  3. int reverse(int x){
  4.     int n = 0;
  5.     int r = 0;
  6.    
  7.     bool is_negative = false;
  8.     if (x < 0) {
  9.         is_negative = true;
  10.     }
  11.     if (x == INT_MIN) {
  12.         return 0;
  13.     }
  14.     int y = abs(x);
  15.     while (y >= 0) {
  16.         r = y % 10;
  17.         if ((y / 10)== 0) {
  18.            if (n > (INT_MAX / 10)) {
  19.                return 0;
  20.            } else if ((n == (INT_MAX / 10)) && is_negative && (r > ((INT_MAX % 10) + 1))) {
  21.                return 0;
  22.            } else if ((n == (INT_MAX / 10)) && !is_negative && (r > (INT_MAX % 10))) {
  23.                return 0;
  24.            } else {
  25.                n = (n * 10) + r;
  26.                if (is_negative) {
  27.                    return (n * -1);
  28.                } else {
  29.                    return n;
  30.                }
  31.            }
  32.         } else {
  33.             n = (n * 10) + r;
  34.             y = y / 10;
  35.         }
  36.     }  
  37.     return -1;
  38. }
复制代码

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

本帖被以下淘专辑推荐:

小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

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

本版积分规则

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

GMT+8, 2025-4-21 14:47

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

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