LeetCode Reverse Integer
递归主要有两个点,一个是它递归的过程是怎么样的,一个就是递归的边界。
#include "pch.h" #include <iostream> using namespace std; class Solution { typedef long long LL; LL ret = 0; bool isOverFlow = false; public : int reverse(LL x) { if (x == 0 || isOverFlow) { return 0; } LL value = abs(x); ret = ret * 10 + value % 10; if (ret>INT_MAX) { isOverFlow = true; } reverse(x/10); return isOverFlow=true?0:(x>0?ret:-ret); } };
#include "pch.h" #include <iostream> using namespace std; class Solution { typedef long long LL; LL ret = 0; bool isOverFlow = false; public : int reverse(LL x) { /* if (x == 0 || isOverFlow) { return 0; } LL value = abs(x); ret = ret * 10 + value % 10; if (ret>INT_MAX) { isOverFlow = true; } reverse(x/10); return isOverFlow=true?0:(x>0?ret:-ret); */ LL value = abs(x); while (value!=0) { if (x == 0 || isOverFlow == true) { return 0; } ret = ret*10+value % 10; if (ret > INT_MAX) { isOverFlow = true; return 0; } value = value / 10; } return isOverFlow ? 0 : (x > 0 ? ret : -ret); } };