每日一道Leetcode - 面试题 08.05. 递归乘法

在这里插入图片描述
感觉就是用数学的思路

class Solution {
    
    
    public int multiply(int A, int B) {
    
    
        if(A==0 || B==0){
    
    
            return 0;
        }
        if(B == 1) return A;
        if(B<0){
    
    
            B = -B;
            return -fun(A,B);
        }
        return fun(A,B);
    }
    public int fun(int m,int n){
    
    
        if(n==1) return m;
        if(n%2 == 0){
    
    
            int half = fun(m,n/2);
            return half + half;
        }else{
    
    
            int half = fun(m,n/2);
            return half+half+m;
        }
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_41041275/article/details/111516247
今日推荐