在 C++ 中查找 N%(余数为 4)的 N 值
在本问题中,我们给定一个表示大整数的字符串 num。我们的任务是查找 N%(余数为 4)的 N 值。
问题描述 − 我们将找到该数字余 4 的余数。
我们举个例子来理解一下这个问题,
输入
num = 453425245
输出
1
解决方案
解决此问题的简单方法是利用这样一个事实,即数字余 4 的余数可以用该数字的最后两位数字来找到。因此,对于任何大数字,我们可以通过将数字的最后两位除以 4 来找到余数。
程序来说明我们解决方案的工作原理,
示例
#include <bits/stdc++.h>
using namespace std;
int calc4Mod(string num, int len) {
int rem;
if (len == 1)
rem = num[0] - '0';
else
rem = (num[len - 2] - '0') * 10 + num[len - 1] - '0';
return (rem % 4);
}
int main() {
string num = "84525765476513";
int len = num.length();
cout<<"The remainder of the number with 4 is "<<calc4Mod(num, len);
return 0;
}输出
The remainder of the number with 4 is 1
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android(安卓)
Python(蟒蛇)
C 编程
C++(C 升级版)
C#(C 锐化)
MongoDB
MySQL
JavaScript( جاوا脚本)
PHP