Math Algorithm Problems

Made by Mike_Zhang


数据结构与算法题主题:


Add Strings

LeetCode Problem #415

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
class Solution {
public String addStrings(String num1, String num2) {
int size1 = num1.length();
int size2 = num2.length();
int p1 = size1-1;
int p2 = size2-1;
StringBuilder out = new StringBuilder();
int c = 0;
while (p1>=0 || p2>=0) {
int n1 = 0;
int n2 = 0;
if (p1>=0) {
n1 = num1.charAt(p1--)-'0';
}
if (p2>=0) {
n2 = num2.charAt(p2--)-'0';
}
int temp = n1+n2+c;
out.insert(0,String.valueOf(temp%10));
c = temp>=10? 1:0;
}
if (c>0) out.insert(0,String.valueOf(1)); // add the final carry out
return out.toString();
}
}

Reverse Integer

LeetCode Problem #7

Java Solution:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Solution {
public int reverse(int x) {
boolean neg = false;
if (x<0) {
x= -x;
neg = true;
}
long out = 0;
while (x>0) {
int last = x%10;
x = x/10;
out = out * 10 + last;
}
if (out>Integer.MAX_VALUE) return 0;
if (neg) return (int)-out;
return (int)out;
}
}

Python Solution:

1
2
3
4
5
6
7
8
9
10
11
12
13
class Solution:
def reverse(self, x: int) -> int:
inX = abs(x)
out = 0
while (inX>0):
out = out * 10 + inX % 10
inX = inX // 10
if out not in range(-2**31,2**31):
return 0
if (x > 0):
return out
else:
return -out

2022-10-06


Maximum Product of Three Numbers

LeetCode Problem #628

1
2
3
4
5
6
7
8
9
10
class Solution {
public int maximumProduct(int[] nums) {

// M1 Sorting
int size = nums.length;
Arrays.sort(nums);
return Math.max(nums[0]*nums[1]*nums[size-1], nums[size-3]*nums[size-2]*nums[size-1]);

}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
class Solution {
public int maximumProduct(int[] nums) {

// M2 Looping
int min1 = Integer.MAX_VALUE; // the smallest
int min2 = Integer.MAX_VALUE; // the second smallest

int max1 = Integer.MIN_VALUE; // the largest
int max2 = Integer.MIN_VALUE; // the second largest
int max3 = Integer.MIN_VALUE; // the third largest

for (int n:nums) {
if (n<=min1) { // n become the new smallest
min2 = min1;
min1 = n;
} else if (n<=min2) { // n become the new second smallest
min2 = n;
}

if (n>=max1) { // n become the new largest
max3 = max2;
max2 = max1;
max1 = n;
}
else if (n>=max2) { // n become the new second largest
max3 = max2;
max2 = n;
}
else if (n>=max3) { // n become the new third largest
max3 = n;
}
}

return Math.max(min1*min2*max1, max3*max2*max1);
}
}

2022-10-12


Last updated on 2022-11-25


References

Math - LeetCode


写在最后

Math Algorithm 相关的知识会继续学习,继续更新.
最后,希望大家一起交流,分享,指出问题,谢谢!


原创文章,转载请标明出处
Made by Mike_Zhang




感谢你的支持

Math Algorithm Problems
https://ultrafish.io/post/math-algo-problems/
Author
Mike_Zhang
Posted on
November 25, 2022
Licensed under