本篇同步发布於Blog:[解题] LeetCode - 7 Reverse Integer
LeetCode
7 - Reverse Integer
https://leetcode.com/problems/reverse-integer/
给一个32位元的整数x,求他的位数反转。但如果反转後的位数会overflow,则回传0。
比如x = 123,答案为321;x = -123,答案为-321;x = 1234567899,答案为0。
建立一个long的变数ans,不断地将x的第1位数转成ans新的进位数。最终再用Math函式库的abs检查是否ans超出32位元整数的最大值,超过就回传0,否则回传转型32位元的ans。
难度为Easy
#include <iostream>
#include <cmath>
#include <climits>
using namespace std;
class Solution {
public:
int reverse(int x) {
long ans = 0;
while(x != 0){
ans = ans * 10 + (x % 10);
x /= 10;
}
return fabs(ans) > INT_MAX ? 0 : ans;
}
};
int main() {
Solution sol;
cout << sol.reverse(123) << endl;
cout << sol.reverse(-123) << endl;
cout << sol.reverse(1234567899) << endl;
return 0;
}
using System;
namespace LeetCode7
{
public class Solution {
public int Reverse(int x) {
long ans = 0;
while(x != 0){
ans = ans * 10 + (x % 10);
x /= 10;
}
return Math.Abs(ans) > Int32.MaxValue ? 0 : (int)ans;
}
}
public class Program
{
public static void Main()
{
Solution sol = new Solution();
Console.WriteLine(sol.Reverse(123));
Console.WriteLine(sol.Reverse(-123));
Console.WriteLine(sol.Reverse(1234567899));
Console.Read();
}
}
}
https://github.com/u8989332/ProblemSolving/blob/master/LeetCode/C%2B%2B/1-99/7.cpp
https://github.com/u8989332/ProblemSolving/blob/master/LeetCode/C%23/1-99/7.cs
<<: DAY 26 Django 简易入门教学(三)-建立 Django 专案与 APP
Android 10以上就很简单,直接使用MediaStore抓到图片路径,然後送给图片剪裁就好 i...
Aloha!又是我少女人妻 Uerica!自从写了铁人赛文章後,因为我跟老公都太忙,我家狗狗对我发出...
Day4 接下来卡比要是着操作 LaserCannon,让他可以左右移动。 Input 在上个章节,...
函式的作用在於将一段或多段函式包装在一起,方便反覆使用,一目了然也方便维护。当需要重复执行一次计算...
最近的工作专案很常用到 button 按钮 因为小公司的关系没有设计 所以通常要自已想 button...