7.4---加法替代运算(CC150)

注意:1,除法那里b+=b是错的。b一直在改变。

     2,仔细一点。

import java.util.*;

public class AddSubstitution {
    public int calc(int a, int b, int type) {
        // write code here
        if(type == 1){
            return multiply(a,b);
        }
        else if(type == 0){
            return divide(a,b);
        }
        else{
            return minus(a,b);
        }
    }

    public static int minus(int a, int b){
        int ans = 0; 
        ans = a + negate(b);

        return ans;
    }
    public static int negate(int a){
        int ans = 0;
        int d = a > 0 ? -1 : 1;
        while(a != 0){
            a+=d;
            ans += d;

        }
        return ans;
    }

    public static int multiply(int a, int b){
        int ans = 0;
        if(a > 0 && b > 0){
            for(int i = 0; i < a; i++){
                ans += b;
            }
        }
        else if(a < 0 && b < 0){
            for(int i = 0; i < Math.abs(a); i++){
                ans += Math.abs(b);
            }
        }
        else if(a > 0){
            for(int i = 0; i < a; i++){
                ans+=b;
            }
        }
        else{
            for(int i = 0; i < b; i++){
                ans += a;
            }
        }
        return ans;

    }

    public static int divide(int A, int B){
        if(B == 0){
            return 0;
        }
        int ans = 0; 
        
        int a = Math.abs(A);
        int b = Math.abs(B);
        int tmp = b;
        if(a >= b){
            for(int i = 1; ; i++){
                if(a == tmp ){
                    ans = i;
                    break;
                }
                if(tmp > a){
                    ans = i - 1 ;
                    break;
                }
                tmp += b;

            }
        }
        else{
            ans = 0;
        }
        if(A > 0 && B > 0 || A<0 && B < 0){
            return ans;
        }
        else{
            return negate(ans);
        }
    }


}

 

posted @ 2015-12-28 15:45  创业-李春跃-增长黑客  阅读(242)  评论(0编辑  收藏  举报