C++程式:求大數除以11的餘數


在這個問題中,我們給定一個表示大數的字串 num。我們的任務是建立一個 C++ 程式來求這個大數除以 11 的餘數。

問題描述 − 我們需要找到由字串定義的數字除以 11 的餘數。

讓我們舉個例子來理解這個問題

輸入

num = “43212981843718452”

輸出

7

解決方案

為了找到餘數,我們顯然需要進行除法運算。但是,除以巨大的數字是一個複雜的過程,為了簡化這個過程,我們將逐位進行除法。並存儲隨之而來的餘數。此過程需要對包含從 MSB 到 LSB 的數字的整個字串繼續進行。最後列印餘數。

程式說明解決方案的工作原理

示例

 線上演示

#include <iostream>
#include <string.h>
using namespace std;
int calcRem(string num){
   int currDigit, rem = 0;
   for (int i = 0; i < num.length(); i++) {
      currDigit = rem * 10 + (num[i] - '0');
      rem = currDigit % 11;
   }
   return rem;
}
int main() {
   string num = "43212981843718452";
   cout<<"The remainder when large number is divided by 11 is"<<calcRem(num);
   return 0;
}

輸出

The remainder when large number is divided by 11 is 7

更新於: 2020年9月17日

427 次瀏覽

開啟你的職業生涯

透過完成課程獲得認證

開始學習
廣告