LC231. 2 的幂
//考察的是对二进制的二次幂在计算机底层的2进制位数是怎么样的,根据观察规律发现n 和n - 1 求与运算永远是0
class Solution {
public boolean isPowerOfTwo(int n) {
return n > 0 && ((n & (n - 1)) == 0);
}
}
LC977. 有序数组的平方
class Solution {
public int[] sortedSquares(int[] nums) {
int left = 0;
int right = nums.length - 1;
int[] res = new int[nums.length];
int index = res.length - 1;
while(left <= right){
if(nums[right]*nums[right] > nums[left]*nums[left]){
res[index--] = nums[right]*nums[right];
right--;
}else {
res[index--] = nums[left]*nums[left];
left++;
}
}
return res;
}
}
LC617. 合并二叉树
//合并两个树的方法就是将两棵树的val值相加,那么如果一个为空就取另一个,如果有两个参数就要考虑两个为空的情况。
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public TreeNode mergeTrees(TreeNode root1, TreeNode root2) {
if(root1 == null){
return root2;
}
if(root2 == null){
return root1;
}
TreeNode merged = new TreeNode(root1.val + root2.val);
merged.left = mergeTrees(root1.left,root2.left);
merged.right = mergeTrees(root1.right,root2.right);
return merged;
}
}