Jian Zhi offer 14- II. Cut the rope II

Jian Zhi offer 14- II. Cut the rope II

Title description

Insert picture description here

Problem-solving ideas

This question is based on cutting the rope I, and there is one more remainder, so you can't use the Math.pow method, you need to implement the exponentiation yourself.

Fast exponentiation is used here, which can be used as a template. Time is o (logn) and space is o (1). The main optimization point is to use the right shift operator to replace the division by 2, and the bitwise AND operator to replace the remainder to determine whether a number is odd or even.

Note, why use the long type for exponents of fast powers?

Because the range of int is [-2 31,2^31-1], the range of negative numbers is larger than that of positive numbers, so you cannot simply take the absolute value. If the base is exactly -2 31 and the exponent is of type int, it will overflow.

class Solution {
    
    
    private int mod = 1000000007;

    public int cuttingRope(int n) {
    
    
        if (n <= 3) {
    
    
            return n - 1;
        }
        int quotient = n / 3;
        int remainder = n % 3;
        if (remainder == 0) {
    
    
            return (int)quickPow(3, quotient);
        } else if (remainder == 1) {
    
    
            return (int)(quickPow(3, quotient - 1) * 4 % mod);
        } else {
    
    
            return (int)(quickPow(3, quotient) * 2 % mod);
        }
    }
    //快速幂模板, 注意指数 exponent 是 long 类型防止溢出,且为非负数
    public long quickPow(long base, long exponent) {
    
    
        if (exponent == 0) return 1;
        if (exponent == 1) return base;

        long res = quickPow(base, exponent >> 1);
        res = (res * res) % mod;
        //如果是奇数,则要额外乘上base
        if ((exponent & 0x01) == 1)
            res = (res * base) % mod;
        return res;
    }
}

Guess you like

Origin blog.csdn.net/cys975900334/article/details/114791460
Recommended