在 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
廣告