# Math

#### [7. Reverse Integer](https://leetcode.com/problems/reverse-integer/)

Stop the loop before `res` exceeded the `limit`.&#x20;

```java
def reverse(self, x: int) -> int:
    limit = pow(2, 31) - 1
    neg = x < 0
    res = 0
    x = abs(x)
    while x > 0:
        if res > limit / 10 and int(x % 10) != 0:
            return 0
        res = res * 10 + int(x % 10)
        x = x // 10
    if neg:
        return res * -1
    return res
```

#### [12. Integer to Roman](https://leetcode.com/problems/integer-to-roman/)

Store int value and its corresponding symbol values in two arrays. `While(num >= arr[i])` append result.

```java
int[] arr = { 1,4,5,9,10,40,50,90,100,400, 500, 900, 1000};
String[] symbol = {"I", "IV", "V", "IX", "X", "XL", "L", "XC", "C", "CD", "D", "CM", "M"};
public String intToRoman(int num) {
    StringBuilder sb = new StringBuilder();
    for (int i = arr.length - 1; i >= 0; i--) {
        while (num >= arr[i]) {
            sb.append(symbol[i]);
            num -= arr[i];
        }
    }
    return sb.toString();
}
```

#### [13. Roman to Integer](https://leetcode.com/problems/roman-to-integer/)

```java
    public int romanToInt(String s) {
        Map<Character, Integer> map = new HashMap<>();
        map.put('M', 1000);
        map.put('D', 500);
        map.put('C', 100);
        map.put('L', 50);
        map.put('X', 10);
        map.put('V', 5);
        map.put('I', 1);
        int res = 0;
        for (int i = 0; i < s.length(); i++) {
            if (i + 1 < s.length()) {
                if (map.get(s.charAt(i)) < map.get(s.charAt(i + 1))) {
                    res += map.get(s.charAt(i + 1)) - map.get(s.charAt(i));
                    i++;
                } else {
                    res += map.get(s.charAt(i));
                }
            } else {
                res += map.get(s.charAt(i));
            }
        }
        return res;
    }
```

#### [67. Add Binary](https://leetcode.com/problems/add-binary/)

```java
public String addBinary(String a, String b) {
    int i = a.length() - 1;
    int j = b.length() - 1;
    StringBuilder sb = new StringBuilder();
    int carry = 0;
    while (i >= 0 || j >= 0) {
        int one = i >= 0 ? a.charAt(i) - '0': 0;
        int two = j >= 0 ? b.charAt(j) - '0': 0;
        int sum = one + two + carry;
        sb.append(sum % 2);
        carry = sum / 2;
        i--;
        j--;
    }
    if (carry == 1) sb.append(1);
    return sb.reverse().toString();
}
```

#### [50. Pow(x, n)](https://leetcode.com/problems/powx-n/)

&#x20;   2^10 = 2\*2\*2\*2\*2\*2\*2\*2\*2\*2

&#x20;   (2\*2)\*(2\*2)\*(2\*2)\*(2\*2)\*(2\*2)

&#x20;   4^5 = (4\*4)\*(4\*4)\*4   &#x20;

&#x20;   16\*2 \* 4

{% tabs %}
{% tab title="Java" %}
```java
public double myPow(double x, int n) {
    if (n == 0) return 1.0;
    if (n == 1) return x;
    double res = 1.0;
    long longn = n;
    longn = longn < 0 ? -longn : longn;
    while (longn > 0) {
        if (longn % 2 != 0) {
            res *= x;
        } 
        x *= x;
        longn /= 2;
    }
    return n < 0 ? 1.0 / res : res;
}
```
{% endtab %}

{% tab title="Python" %}
```python
def myPow(self, x: float, n: int) -> float:
    negative = n < 0
    i = abs(n)
    res = 1.0
    while i > 0:
        if i % 2 != 0:
            res *= x
        x *= x
        i = i // 2
    if negative:
        return 1.0 / res
    return res
```
{% endtab %}
{% endtabs %}

#### [273. Integer to English Words](https://leetcode.com/problems/integer-to-english-words/)

```java
    String[] LESS20 = {"", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen"};
    String[] TENs = {"", "Ten", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"};
    String[] THOUSANDs = {"", "Thousand", "Million", "Billion"};
    public String numberToWords(int num) {
        if (num == 0) return "Zero";
        int i = 0;
        String res = "";
        while (num != 0) {
            if (num % 1000 != 0) {
                res = helper(num % 1000) + THOUSANDs[i] + " " + res;
            }
            i++;
            num /= 1000;
        }
        return res.trim();
    }
    
    private String helper(int n) {
        if (n == 0) return "";
        if (n < 20) return LESS20[n] + " ";
        else if (n < 100) return TENs[n / 10] + " " + helper(n % 10);
        return LESS20[n / 100] + " Hundred " + helper(n % 100);
    }
```

#### 1131. Maximum of Absolute Value Expression

Solve the equation by:

![](https://249794273-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-Laur3QE_YAExtEZegFt%2F-MFgFNEqtxJ-Rp4snvi_%2F-MFgLIX63xysiQM2gwg8%2Fimage.png?alt=media\&token=3a807046-c2a6-4e15-ab7c-bd507f1a9fe0)

Then detect the maximum result of `max - min`

```java
public int maxAbsValExpr(int[] arr1, int[] arr2) {
    int max1 = Integer.MIN_VALUE;
    int max2 = Integer.MIN_VALUE;
    int max3 = Integer.MIN_VALUE;
    int max4 = Integer.MIN_VALUE;
    int min1 = Integer.MAX_VALUE;
    int min2 = Integer.MAX_VALUE;
    int min3 = Integer.MAX_VALUE;
    int min4 = Integer.MAX_VALUE;
    for (int i = 0; i < arr1.length; i++) {
        max1 = Math.max(max1, arr1[i] + arr2[i] + i);
        max2 = Math.max(max2, arr1[i] + arr2[i] - i);
        max3 = Math.max(max3, arr1[i] - arr2[i] - i);
        max4 = Math.max(max4, arr1[i] - arr2[i] + i);
        min1 = Math.min(min1, arr1[i] + arr2[i] + i);
        min2 = Math.min(min2, arr1[i] + arr2[i] - i);
        min3 = Math.min(min3, arr1[i] - arr2[i] - i);
        min4 = Math.min(min4, arr1[i] - arr2[i] + i);
    }
    return Math.max(Math.max(max1 - min1, max2 - min2), Math.max(max3 - min3, max4 - min4));
}
```

#### [470. Implement Rand10() Using Rand7()](https://leetcode.com/problems/implement-rand10-using-rand7/)

[How to do question like implement RandomX by RandomY.](https://leetcode.com/problems/implement-rand10-using-rand7/discuss/150301/Three-line-Java-solution-the-idea-can-be-generalized-to-%22Implement-RandM\(\)-Using-RandN\(\)%22)

![](https://249794273-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-Laur3QE_YAExtEZegFt%2F-MMMdE7FFaq5d3B9dxmn%2F-MMMg4bDLGVFu5tjAakH%2Fimage.png?alt=media\&token=0984b322-1794-4f90-92c9-be0f96fea177)

```java
public int rand10() {
    int res = 40;
    while (res >= 40) {
        res = (rand7() - 1) * 7 + rand7() - 1;
    }
    return res % 10 + 1;
}
```

[2918. Minimum Equal Sum of Two Arrays After Replacing Zeros](https://leetcode.com/problems/minimum-equal-sum-of-two-arrays-after-replacing-zeros/)

```typescript
function minSum(nums1: number[], nums2: number[]): number {
    let sum1 = 0, countZero1 = 0;
    for (const num of nums1) {
        sum1 += num;
        if (num === 0) {
            countZero1++;
            sum1++;
        }
    }
    let sum2 = 0, countZero2 = 0;
    for (const num of nums2) {
        sum2 += num;
        if (num === 0) {
            countZero2++;
            sum2++;
        }
    }
    if ((countZero1 === 0 && sum2 > sum1) || (countZero2 === 0 && sum1 > sum2)) return -1;
    return Math.max(sum1, sum2);
};
```

[3335. Total Characters in String After Transformations I](https://leetcode.com/problems/total-characters-in-string-after-transformations-i/)

```typescript
function lengthAfterTransformations(s: string, t: number): number {
    const MOD = 1_000_000_007;
    const freq: number[] = new Array(26).fill(0);
    for (const c of s) {
        freq[c.charCodeAt(0) - 'a'.charCodeAt(0)]++;
    }

    let zIdx = 25;
    while (t-- > 0) {
        const next = (zIdx + 1) % 26;
        freq[next] = (freq[next] + freq[zIdx]) % MOD;
        zIdx = (zIdx - 1 + 26) % 26;
    }
    let result = 0;
    for (const f of freq) {
        result = (result + f) % MOD;
    }

    return result;
};
```
