1、整数反转
- 给出一个 32 位的有符号整数,你需要将这个整数中每位上的数字进行反转。
输入: 123
输出: 321
输入: -123
输出: -321
输入: 120
输出: 21
- 注意:假设我们的环境只能存储得下 32 位的有符号整数,则其数值范围为 [
−2^31
,2^31 − 1
]。请根据这个假设,如果反转后整数溢出那么就返回 0。
我的代码:
public static int reverse(int x) {
//思路:
/*
* 1、将该数字每一个数字从后向前依次取出来,放在数组里面
* 2、计算出反转之后的数字然后输出
* */
//记录这个数字的正负
char c = ' ';
if (x >= 0) {
c = '+';
} else {
c = '-';
}
//计算该数字的位数
int temp = x;
int weishu = 0;
while (temp != 0) {
temp /= 10;
weishu++;
}
//反向获取该数字的每一位,然后存放在数组里面
int[] arr = new int[weishu];
//定义角标表示数组的下标
int index = 0;
int num = 0;
x = Math.abs(x);
while (x != 0) {
num = x % 10;
x /= 10;
arr[index] = num;
index++;
}
int result = 0;
for (int i = 0; i < arr.length; i++) {
result += arr[i] * Math.pow(10, arr.length - i - 1);
}
if (result <= Integer.MIN_VALUE || result >= Integer.MAX_VALUE) {
return 0;
}
if (c == '-') {
result = -result;
}
return result;
}
官方解释:
public static int reverse(int x) {
int result = 0;
while (x != 0) {
int pop = x % 10;
x /= 10;
if ((result > Integer.MAX_VALUE / 10) || (result == Integer.MAX_VALUE / 10 && pop > 7)) {
return 0;
}
if ((result < Integer.MIN_VALUE / 10) || result == Integer.MIN_VALUE / 10 && pop < -8) {
return 0;
}
result = result * 10 + pop;
}
return result;
}
首先代码从一个
while
循环开启,解析出这个数字当前的最后一位数字,并且减少该数字一位位数,如果当前的结果不在整数范围之内,就直接返回0,否则的话让当前的结果乘以10,扩大十倍,并加上解析出来的最后一个数字;
2、合并二叉树
class Solution {
public TreeNode mergeTrees(TreeNode t1, TreeNode t2) {
if (t1 == null) {
return t2;
}
if (t2 == null) {
return t1;
}
TreeNode merged = new TreeNode(t1.val + t2.val);
merged.left = mergeTrees(t1.left, t2.left);
merged.right = mergeTrees(t1.right, t2.right);
return merged;
}
}
上面的做法是一个官方给出来的 深度优先算法,比较好理解:
核心思想是使用到了递归,该方法里面只产生一个根节点的值以及它的左右节点,并且左右节点的值是未知的,交给下一次的递归计算,代码很简洁,理解起来很容易;