Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 542c263

Browse files
solves divide two integers
1 parent 4b446eb commit 542c263

File tree

2 files changed

+17
-0
lines changed

2 files changed

+17
-0
lines changed

‎README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,7 @@
3535
| 26 | [Remove Duplicates From Sorted Array](https://leetcode.com/problems/remove-duplicates-from-sorted-array/) | [![Java](assets/java.png)](src/RemoveDuplicatesFromSortedArray.java) [![Python](assets/python.png)](python/remove_duplicates_from_sorted_array.py) | |
3636
| 27 | [Remove Element](https://leetcode.com/problems/remove-element/) | [![Java](assets/java.png)](src/RemoveElement.java) [![Python](assets/python.png)](python/remove_element.py) | |
3737
| 28 | [Needle in Haystack](https://leetcode.com/problems/implement-strstr) | [![Java](assets/java.png)](src/NeedleInHaystack.java) [![Python](assets/python.png)](python/needle_in_haystack.py) | |
38+
| 29 | [Divide Two Integers](https://leetcode.com/problems/divide-two-integers) | [![Java](assets/java.png)](src/DivideTwoIntegers.java) | |
3839
| 35 | [Search Inserted Position](https://leetcode.com/problems/search-insert-position/) | [![Java](assets/java.png)](src/SearchInsertPosition.java) [![Python](assets/python.png)](python/search_insert_position.py) | |
3940
| 38 | [Count and Say](https://leetcode.com/problems/count-and-say) | [![Java](assets/java.png)](src/CountAndSay.java) [![Python](assets/python.png)](python/count_and_say.py) | |
4041
| 53 | [Maximum SubArray](https://leetcode.com/problems/maximum-subarray) | [![Java](assets/java.png)](src/MaximumSubArray.java) [![Python](assets/python.png)](python/maximum_sum_subarray.py) | |

‎src/DivideTwoIntegers.java

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
// https://leetcode.com/problems/divide-two-integers
2+
// T: O(A / B)
3+
// S: O(1)
4+
5+
public class DivideTwoIntegers {
6+
public int divide(int A, int B) {
7+
if (A == 1 << 31 && B == -1) return (1 << 31) - 1;
8+
int a = Math.abs(A), b = Math.abs(B), res = 0, x = 0;
9+
while (a - b >= 0) {
10+
for (x = 0; a - (b << x << 1) >= 0; x++);
11+
res += 1 << x;
12+
a -= b << x;
13+
}
14+
return (A > 0) == (B > 0) ? res : -res;
15+
}
16+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /