• [算法练习]Reverse Integer


    题目说明:

    Reverse digits of an integer.

    Example1: x = 123, return 321
    Example2: x = -123, return –321

    程序代码:

    #include <gtest/gtest.h>
    using namespace std;
    
    int reverse2(int x) 
    {
        int result[20] = {0};
        int resultIdx = 0;
        int sign = 1;
        long long val = x;
        if (val < 0)
        {
            sign = -1;
            val = -val;
        }
    
        while (val)
        {
            result[resultIdx++] = val % 10;
            val /= 10;
        }
    
        long long newResult = 0;
        long long base = 1;
        for (int i = resultIdx-1; i >= 0; i--)
        {
            newResult += result[i] * base;
            base *= 10;
        }
    
        if (newResult > 0x7FFFFFFF)
        {
            newResult = 0;
        }
    
        newResult *= sign;
    
        return (int)newResult;
    }
    
    int reverse(int x) 
    {
        int result[20] = {0};
        int resultIdx = 0;
    
        while (x)
        {
            result[resultIdx++] = x % 10;
            x /= 10;
        }
    
        long long newResult = 0;
        long long base = 1;
        for (int i = resultIdx-1; i >= 0; i--)
        {
            newResult += result[i] * base;
            base *= 10;
        }
    
        if ((newResult > 0x7FFFFFFF) || (newResult < -0x7FFFFFFF))
        {
            newResult = 0;
        }
    
        return (int)newResult;
    }
    
    TEST(Pratices, tReverse)
    {
        // 123 -> 321
        ASSERT_EQ(reverse(123),321);
        // -123 -> -321
        ASSERT_EQ(reverse(-123),-321);
        // 0 -> 0
        ASSERT_EQ(reverse(0),0);
        // -0 -> 0
        ASSERT_EQ(reverse(-0),0);
        // 0x1FFFFFFF -> 0x7FFFFFFF
        ASSERT_EQ(reverse(-2147483648),0);
        // -0x1FFFFFFF -> -0x7FFFFFFF
        //ASSERT_EQ(reverse(-0x1FFFFFFF),-0x7FFFFFFF);
    }
  • 相关阅读:
    iOS热更新-8种实现方式
    HTTPS分析-简单易懂
    猖獗的假新闻:2017年1月1日起iOS的APP必须使用HTTPS
    iOS的ATS配置
    Objective-C中block的底层原理
    iOS系列文章
    UIViewController生命周期-完整版
    缩放因子和UI设计
    iOS APP 如何做才安全
    逆向工程
  • 原文地址:https://www.cnblogs.com/Quincy/p/5290025.html
Copyright © 2020-2023  润新知