程序员面试金典 - 面试题 16.09. 运算(只用+法做乘除)
生活随笔
收集整理的這篇文章主要介紹了
程序员面试金典 - 面试题 16.09. 运算(只用+法做乘除)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
1. 題目
請實現整數數字的乘法、減法和除法運算,運算結果均為整數數字,
程序中只允許使用加法運算符和邏輯運算符,允許程序中出現正負常數,不允許使用位運算。
你的實現應該支持如下操作:
- Operations() 構造函數
- minus(a, b) 減法,返回a - b
- multiply(a, b) 乘法,返回a * b
- divide(a, b) 除法,返回a / b
來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/operations-lcci
著作權歸領扣網絡所有。商業轉載請聯系官方授權,非商業轉載請注明出處。
2. 解題
參考題解:把乘數和除數的 2n2^n2n 倍的結果 存起來,不斷的加或者減
class Operations { public:Operations() {}int minus(int a, int b) {return a+(-b);}int multiply(int a, int b) {if(a==0 || b==0) return 0;if(a==1) return b;if(b==1) return a;if(a== -1) return -b;if(b== -1) return -a;int negative = 0;if(a < 0) negative += 1, a = -a;if(b < 0) negative += 1, b = -b;if(a > b) swap(a,b);// b*along temp = b;vector<int> b_2, count;int plus = 1;while(temp <= INT_MAX)//b_2數組[b*1,b*2,b*4...]{ b_2.push_back(temp);count.push_back(plus);//b乘以幾得到上面的數temptemp += temp;plus += plus;}int ans = 0;for(int i = b_2.size()-1; i >= 0; i=minus(i,1)){while(a >= count[i]){ans += b_2[i];a = minus(a,count[i]);//把a拆分}}if(negative==1)return -ans;return ans;}int divide(int a, int b) {if(a==0 || b==INT_MAX || b==INT_MIN) return 0;if(b==1) return a;if(b== -1) return -a;int negative = 0;if(a < 0) negative += 1, a = -a;if(b < 0) negative += 1, b = -b;if(a < b) return 0;long temp = b;vector<int> b_2, count;int plus = 1;while(a >= temp){ b_2.push_back(temp);//[b*1,b*2,b*4,...]count.push_back(plus);//b乘以幾得到上面的數temptemp += temp;plus += plus;}int ans = 0;for(int i = b_2.size()-1; i >= 0; i=minus(i,1)){while(a >= b_2[i]){ans += count[i];//商+倍數a = minus(a,b_2[i]);//把a減去b的倍數}}if(negative==1)return -ans;return ans;} };84 ms 15 MB
創作挑戰賽新人創作獎勵來咯,堅持創作打卡瓜分現金大獎總結
以上是生活随笔為你收集整理的程序员面试金典 - 面试题 16.09. 运算(只用+法做乘除)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: LeetCode 494. 目标和(DF
- 下一篇: LeetCode 1380. 矩阵中的幸