当前位置: 首页 > news >正文

【算法day8】整数反转

整数反转

https://leetcode.cn/problems/reverse-integer/description/

在这里插入图片描述

class Solution {
public:
    int reverse(int x) {
        int MAX_LENGTH = 11; // 32位整数的最大数字的位数
        int* num = (int*)calloc(sizeof(int), MAX_LENGTH); //用于保存进位每一位的数字
        int current = x;
        int pos = 0;
        while (current != 0 && pos < MAX_LENGTH) {
            num[pos] = current % 10;
            current = current / 10;
            pos++;
        }
        if (pos == MAX_LENGTH) {
            return 0;
        }
        int new_pos = 1;
        int new_num = num[0];
        int highest_carry = 10;
        while (new_pos < pos) {
            long after = new_num;
            after = after * 10 + num[new_pos];
            // 若进位发生了变化,那么返回0,说明出现了溢出,
            if (after % highest_carry != num[new_pos]) {
                return 0;
            } else {
                new_num = after;
            }
            if (after == 0) {
                highest_carry *= 10;
            } else {
                highest_carry = after * 10;
            }
            new_pos++;
        }
        return new_num;
    }
};

相关文章:

  • 【Linux】动/静态库
  • echart x轴标签文字过多显示被重叠的解决办法
  • K8S学习之基础二十五:k8s存储类之storageclass
  • 学习Android Audio 焦点记录
  • leetcode【面试经典150系列】(一)
  • Spring Boot集成HikariCP:原理剖析与实战指南
  • Flink-学习路线
  • DataWhale 大语言模型 - 语言模型发展历程
  • C++算法学习2:二分算法精讲
  • 在 Linux 系统中,区分**磁盘(物理/虚拟存储设备)和分区(磁盘的逻辑划分)
  • 阿里云爆发式的跨越
  • 高等数学-第七版-上册 选做记录 习题4-1
  • 搞定python之三----序列、字典及集合
  • 算法练习——双指针算法(更新中)
  • 【2025】基于springboot+vue的网络安全科普平台(源码、万字文档、图文修改、调试答疑)
  • OpenHarmony子系统开发 - 模块配置规则
  • 3.12-1 html讲解
  • 博客系统自动化测试
  • 20 | 如何添加单元测试用例
  • Hadoop 集群部署与配置详解
  • 咸宁网站建设解决方案/网站运营主要做什么
  • 怎么做网站广告/百度官方推广平台
  • 深圳网络公司招聘/360优化大师安卓手机版下载安装
  • 国际学校网站建设/新闻20条摘抄大全
  • 昌吉州建设局网站/百度在线客服人工服务
  • 政府网站建设报告/搜狗网页版入口