LeetCode(5)

来源:互联网 发布:印第安人 知乎 编辑:程序博客网 时间:2024/06/06 09:36

7. Reverse Integer

Reverse digits of an integer.

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

click to show spoilers.

Note:
The input is assumed to be a 32-bit signed integer. Your function should return 0 when the reversed integer overflows

好了me 做题的时候再次不看题目下的 notes !!!!!尴尬

这道题本身不太难,很简单,主要要特别 注意 超过 上限和下限的问题 。我自己用的 是一个 charat 循环外加string builder 的方法,但感觉 很笨(因为如果是 double 的 input就不好搞了),尤其是最后 。一个 accept 的答案就是用的余数和除法来做 。其实 这个就体现了计算机 中数学的一个运用。 “程序员的数学”那本书 里面有一章 “余数”,周期性和分组 。这道题 就蛮好的体现了 这个 想法 ,

public int reverse(int x){    int result = 0;    while (x != 0)    {        int tail = x % 10;        int newResult = result * 10 + tail;        if ((newResult - tail) / 10 != result)        { return 0; } //这一段紫色的代表,如果是overflow 的就给我 丢个0回去 。        result = newResult;        x = x / 10;    }    return result;}
 

8. String to Integer (atoi)


 

8. String to Integer (atoi)