使用移位运算符分割一个大小数
16lz
2021-01-22
How to write a program in c to split a large number using shift operator ?
如何用c编写一个程序来使用移位运算符分割一个大的数字?
For example we need to split a large number like 12345678 into two smaller digits 1234 and 5678 using only bit shift operations and not using the normal n=n*10 and n=n%10 technique. How would you do that?
例如,我们需要将一个大的数字(如12345678)分割成两个较小的数字(1234和5678),只使用位移位操作,不使用普通的n=n*10和n=n%10技术。你会怎么做?
2 个解决方案
#1
1
You can use standard long division algorithm and call it with 12345678 and 10000. If you want to optimize it for dividing by 10000 only, pre-evaluate it for b == 10000 by hand.
您可以使用标准的长除法算法,将它调用为12345678和10000。如果你想对它进行优化,只除以10000,用手工对b = 10000进行预估。
void div(int a, int b) {
int d, res;
d = 1;
res = 0;
while (b > 0 && b < a) {
b <<= 1;
d <<= 1;
}
do {
if (a >= b) {
a -= b;
res += d;
}
b >>= 1;
d >>= 1;
} while (d);
printf("Result: %d, reminder: %d\n", res, a);
}
int main() {
div(12345678, 10000);
}
更多相关文章
- 在for循环中生成的数字如何输出它们,就像它们的最高值是1和最低0
- js金额数字格式化实现代码(三位加逗号处理保留两位置小数)
- javascript如何取字符串中的数字
- 密码强度正则表达式与数字[重复]
- 用原生js实现数字自相加
- NodeJS - 解析JSON(只有字符串或数字)
- 固定大小的div不应该将数字分成两半
- 使数字成为另一个数字的因素(性能问题)
- typeescript:在数字上使用parseInt()时出错