zoukankan      html  css  js  c++  java
  • 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);
            }
        }
    
    
    }
  • 相关阅读:
    jedis操作redis事务练习
    jedis连接redis,测试操作redis常用的数据类型 String List Set Hash Zset
    多态的理解
    binarySeach方法
    数组重新认识
    String的 认识
    接口的 认识
    抽象类及抽象方法
    protected的深刻理解
    protected的认识
  • 原文地址:https://www.cnblogs.com/yueyebigdata/p/5082804.html
Copyright © 2011-2022 走看看