Math

Stop the loop before res exceeded the limit.

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

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

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();
}

2^10 = 2*2*2*2*2*2*2*2*2*2

(2*2)*(2*2)*(2*2)*(2*2)*(2*2)

4^5 = (4*4)*(4*4)*4

16*2 * 4

1131. Maximum of Absolute Value Expression

Solve the equation by:

Then detect the maximum result of max - min

How to do question like implement RandomX by RandomY.

2918. Minimum Equal Sum of Two Arrays After Replacing Zeros

3335. Total Characters in String After Transformations I

Last updated

Was this helpful?