<分区>
How to write a program in c to split a large number using shift operator ?
例如,我们需要将像 12345678 这样的大数字拆分成两个较小的数字 1234 和 5678,只使用位移操作,而不是使用正常的 n=n*10 和 n=n%10 技术。你会怎么做?
<分区>
How to write a program in c to split a large number using shift operator ?
例如,我们需要将像 12345678 这样的大数字拆分成两个较小的数字 1234 和 5678,只使用位移操作,而不是使用正常的 n=n*10 和 n=n%10 技术。你会怎么做?
最佳答案
您可以使用标准的长除法算法,并使用 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);
}
关于c - 使用移位运算符拆分大十进制数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25945570/