不使用 *、/、+、

编程入门 行业动态 更新时间:2024-10-16 00:18:02
本文介绍了不使用 *、/、+、-、% 运算符将数字除以 3的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

如果不使用*、/、+、-、%,运算符?

How would you divide a number by 3 without using *, /, +, -, %, operators?

该号码可能有符号或无符号.

The number may be signed or unsigned.

推荐答案

这是一个简单函数,执行所需操作.但它需要 + 运算符,所以你剩下要做的就是用位运算符添加值:

This is a simple function which performs the desired operation. But it requires the + operator, so all you have left to do is to add the values with bit-operators:

// replaces the + operator int add(int x, int y) { while (x) { int t = (x & y) << 1; y ^= x; x = t; } return y; } int divideby3(int num) { int sum = 0; while (num > 3) { sum = add(num >> 2, sum); num = add(num >> 2, num & 3); } if (num == 3) sum = add(sum, 1); return sum; }

正如吉姆所说,这是可行的,因为:

As Jim commented this works, because:

  • n = 4 * a + b
  • n/3 = a + (a + b)/3
  • 所以sum += a,n = a + b,然后迭代

当a == 0 (n <4), sum += floor(n/3); 即1, if n== 3,否则为 0

更多推荐

不使用 *、/、+、

本文发布于:2023-11-30 08:51:06,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1649429.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!