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);
}

更多相关文章

  1. 在for循环中生成的数字如何输出它们,就像它们的最高值是1和最低0
  2. js金额数字格式化实现代码(三位加逗号处理保留两位置小数)
  3. javascript如何取字符串中的数字
  4. 密码强度正则表达式与数字[重复]
  5. 用原生js实现数字自相加
  6. NodeJS - 解析JSON(只有字符串或数字)
  7. 固定大小的div不应该将数字分成两半
  8. 使数字成为另一个数字的因素(性能问题)
  9. typeescript:在数字上使用parseInt()时出错

随机推荐

  1. Android视频方向为什么出现问题以及Andro
  2. Android 自定义标题栏(title栏)
  3. Android 中文API (66) —— BluetoothClass
  4. Android 音频播放
  5. Android -很全的android操作内容丰富
  6. Android 一个APK文件部署产生多个应用安
  7. 优酷菜单
  8. 半透明Activity方法
  9. android 设置activity不全屏
  10. TextView的走马灯效果