随笔- 509  文章- 0  评论- 151  阅读- 22万 

2014-03-20 02:16

题目:只用加法和赋值,实现减法、乘法、除法。

解法:我只实现了整数范围内的。减法就是加上相反数。乘法就是连着加上很多个。除法就是减到不能减为止,数数总共减了多少个。

代码:

复制代码
  1 // 7.4 Implement the -*/ function with only the + operator.
  2 // You cannot use bit operation, although you might want it for efficiency.
  3 #include <cstdio>
  4 using namespace std;
  5 
  6 int negate(int n)
  7 {
  8     int one = (n >= 0 ? -1 : 1);
  9     int res = 0;
 10     
 11     while (n != 0) {
 12         n += one;
 13         res += one;
 14     }
 15     
 16     return res;
 17 }
 18 
 19 int add(int x, int y)
 20 {
 21     return x + y;
 22 }
 23 
 24 int subtract(int x, int y)
 25 {
 26     return x + negate(y);
 27 }
 28 
 29 int multiply(int x, int y)
 30 {
 31     int res = 0;
 32     int value = (x >= 0 ? y : negate(y));
 33     int one = (x >= 0 ? -1 : 1);
 34     
 35     while (x != 0) {
 36         res += value;
 37         x += one;
 38     }
 39     
 40     return res;
 41 }
 42 
 43 int divide(int x, int y)
 44 {
 45     if (y == 0) {
 46         return 0;
 47     }
 48     if (x == 0) {
 49         return 0;
 50     }
 51     
 52     int res = 0;
 53     int one = 1;
 54     int negone = -1;
 55     int negy = negate(y);
 56     
 57     if (x > 0) {
 58         if (y > 0) {
 59             while (x >= y) {
 60                 x += negy;
 61                 res += one;
 62             }
 63         } else {
 64             while (x >= negy) {
 65                 x += y;
 66                 res += negone;
 67             }
 68         }
 69     } else {
 70         if (y > 0) {
 71             while (x <= negy) {
 72                 x += y;
 73                 res += negone;
 74             }
 75         } else {
 76             while (x <= y) {
 77                 x += negy;
 78                 res += one;
 79             }
 80         }
 81     }
 82     
 83     return res;
 84 }
 85 
 86 int main()
 87 {
 88     char s[10];
 89     int a, b;
 90     int res;
 91     
 92     while (scanf("%d%s%d", &a, s, &b) == 3) {
 93         switch (s[0]) {
 94         case '+':
 95             res = add(a, b);
 96             break;
 97         case '-':
 98             res = subtract(a, b);
 99             break;
100         case '*':
101             res = multiply(a, b);
102             break;
103         case '/':
104             res = divide(a, b);
105             break;
106         }
107         printf("%d\n", res);
108     }
109     
110     return 0;
111 }
复制代码

 

 posted on   zhuli19901106  阅读(227)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)
点击右上角即可分享
微信分享提示