LeetCode刷题(2)
来源:互联网 发布:7.0神器数据库 编辑:程序博客网 时间:2024/06/05 02:30
4、 Add Digits
Given a non-negative integer num, repeatedly add all its digits until the result has only one digit.
For example:
Given num = 38, the process is like: 3 + 8 = 11, 1 + 1 = 2. Since 2 has only one digit, return it.
Follow up:
Could you do it without any loop/recursion in O(1) runtime?
一个数中的所有数字之和能被9整除,则该数能被9整除。
public class Solution { public int addDigits(int num) { if(num<=9) return num; else if(num%9==0) return 9; else return num%9; }}
public class Solution { public int addDigits(int num) { return 1 + (num-1)%9; }}
5、 Maximum Depth of Binary Tree
Given a binary tree, find its maximum depth.
The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */public class Solution { public int maxDepth(TreeNode root) { if(root==null) return 0; else return 1+Math.max(maxDepth(root.left),maxDepth(root.right)); }}
6、 Invert Binary Tree
Invert a binary tree.
4
/ \
2 7
/ \ / \
1 3 6 9
to
4
/ \
7 2
/ \ / \
9 6 3 1
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */public class Solution { public TreeNode invertTree(TreeNode root) { if(root==null) return null; TreeNode temp = root.left; root.left = invertTree(root.right); root.right = invertTree(temp); return root; }}
public TreeNode invertTree(TreeNode root) { if (root != null) { TreeNode temp = root.left; root.left = root.right; root.right = temp; invertTree(root.left); invertTree(root.right); } return root;}
8 0
- LeetCode刷题(2)
- Leetcode刷题(2)
- LeetCode刷题(2)
- 【leetcode】leetcode 刷题 笔记 (不定期更新)
- LeetCode 刷题2 (digit sum)
- leetcode刷题(2)
- leetcode刷题-堆栈2
- leetcode刷题(Python)
- LeetCode刷题(1)
- LeetCode刷题(3)
- LeetCode刷题(废弃)
- LeetCode刷题(FizzBuzz)
- Leetcode刷题(1)
- Leetcode刷题(3)
- Leetcode刷题(4)
- Leetcode刷题(5)
- Leetcode刷题(6)
- Leetcode刷题(7)
- python 跨文件夹引用
- 软键盘的显示与隐藏
- sigaction() 使用
- MyBatis学习(一)--宏观上把握MyBatis框架
- 如何使用JSONP实现跨域请求?
- LeetCode刷题(2)
- 【剑指offer】查找单链表的中间节点
- [SQLServer 2000 Driver for JDBC][SQLServer]传入的表格格式数据流(TDS)远程过程调用(RPC)协议流不正确
- c语言5
- Android preference XML Attributes
- Java中字符编码和字符串所占字节数
- Android中观察者设计模式的使用
- Perl语言入门(06 正则表达式)
- (frame buffer -> fb0)屏幕设备内存映射操作(1)