Given two integers dividend and divisor, divide two integers without using multiplication, division and mod operator.
Return the quotient after dividing dividend by divisor.
The integer division should truncate toward zero.
Example 1:
Input: dividend = 10, divisor = 3
Output: 3
Example 2:
Input: dividend = 7, divisor = -3
Output: -2
Note:
Both dividend and divisor will be 32-bit signed integers.
The divisor will never be 0.
Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−231, 231 − 1]. For the purpose of this problem, assume that your function returns 231 − 1 when the division result overflows.
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/divide-two-integers
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
//二分查找
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public int closestValue(TreeNode root, double target) {
if(root.left==null && root.right==null) return root.val;
int ans = root.val;
while(root != null){
int tem = root.val;
ans = Math.abs(ans - target) > Math.abs(tem - target) ? tem : ans;
root = tem > target ? root.left : root.right;
}
return ans;
}
}
//迭代中序
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public int closestValue(TreeNode root, double target) {
if(root.left==null && root.right==null) return root.val;
long ans = Long.MIN_VALUE;
Stack<TreeNode> st = new Stack<>();
while(root != null || !st.isEmpty()){
while(root!=null){
st.push(root);
root = root.left;
}
root = st.pop();
int tem = root.val;
if(ans <= target && target < root.val){
return Math.abs(ans - target) < Math.abs(tem - target) ? (int)ans : tem;
}
ans = tem;
root = root.right;
}
return (int)ans;
}
}