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 2014-03-20 02:20  zhuli19901106  阅读(226)  评论(0编辑  收藏  举报