leetcode Sum of Two Integers Calculate the sum of two integers a and b, but you are not allowed to use the operator + and -. Example:Given a = 1 and b = 2, return 3. 求两数只和,不能用加法和减法。
leetcode Sum of Two Integers
Calculate the sum of two integers a and b, but you are not allowed to use the operator + and -.
Example:Given a = 1 and b = 2, return 3.
求两数只和,不能用加法和减法。
a ^ b 表示求和且不进位。a & b 表示按位求与,(a & b) * 2 即为进位。
所以 a + b = ((a & b)<<1) + a ^ b;直到进位为0时。结果就是我们所需要的结果。
12345678910
public class Solution { public int getSum(int a, int b) { while(b!=0){ int c = a & b; a = a ^ b; b = c << 1; } return a; }}
https://leetcode.com/problems/sum-of-two-integers/
正如标题所述,你需要使用两个栈来实现队列的一些操作。
队列应支持push(element),pop() 和 top(),其中pop是弹出队列中的第一个(最前面的)元素。
pop和top方法都应该返回第一个元素的值。
两个栈,stack1与stack2.stack2中元素顺序和入栈顺序完全相反。每次插入时把stack2里所有数据插入到stack1,然后插入元素到stack1末尾,再倒回stack2.
12345678910111213141516171819202122232425262728293031
public class Queue { private Stack<Integer> stack1; private Stack<Integer> stack2; public Queue() { stack1 = new Stack<Integer>(); stack2 = new Stack<Integer>(); } public void push(int element) { if (stack2.empty()){ stack2.push(element); } else { while (!stack2.empty()){ stack1.push(stack2.pop()); } stack1.push(element); while (!stack1.empty()){ stack2.push(stack1.pop()); } } } public int pop() { return stack2.pop(); } public int top() { return stack2.peek(); }}
http://www.lintcode.com/zh-cn/problem/implement-queue-by-two-stacks/
找到单链表倒数第n个节点,保证链表中节点的最少数量为n。
可以选择两个指针,指向第一个(first)和第N个(end)。然后每次first前进一格,则end也前进一格,知道end == null时,first指向的就是倒数第n个。
1234567891011121314
public class Solution { ListNode nthToLast(ListNode head, int n) { ListNode first = head; ListNode end = head; for (int i=0;i<n;i++){ end = end.next; } while(end != null){ end = end.next; first = first.next; } return first; }}
http://www.lintcode.com/zh-cn/problem/nth-to-last-node-in-list/
DiamondYuan
ShangHai
Posts
29
Categories
6
Tags
23
源码解析
LeetCode/LintCode 刷题
Update your browser to view this website correctly. Update my browser now
×