C++中計算數字個數,使得數字與其數字之和的差值不小於L


給定一個數字N和另一個數字L。目標是在1到N之間找到那些數字本身與其各位數字之和的差值不小於L的數字。

如果N=23,L=10,則此類數字的個數為4。

23-(2+3)=18, 22-(2+2)=18, 21-(2+1)=18, 20-(2+0)=18.

以上所有數字都滿足條件

但是19-(1+9)=9小於L,類似地,18,17……1。

讓我們透過例子來理解

輸入 − N=30 L=19

輸出 − 數字與其數字之和的差值不小於L的數字個數為 − 1

解釋 − 只有30滿足條件,30-(3+0)=27 > 19

輸入 − N=123330 L=5466

輸出 − 數字與其數字之和的差值不小於L的數字個數為 − 6841

下面程式中使用的演算法如下:

使用二分查詢找到第一個滿足條件的數字。如果該數字為num,則num+1及之後的所有數字也滿足該條件。

如果任何當前中間值滿足條件,則中間值和結束值之間的所有數字也滿足此條件,因此我們可以簡單地將end-mid+1新增到計數中。

  • 將num和L作為長整型變數。

  • 函式Digit_sum(LL num)接受一個數字num並返回其各位數字之和。

  • 將初始和設定為total=0。

  • 使用while迴圈,將餘數num%10新增到total中,並將num減少10。重複此操作,直到num>0。

  • 返回total作為num的各位數字之和。

  • 函式Less_than_L(LL num, LL L)接受一個數字num和一個數字L,並返回數字與其數字之和的差值不小於L的數字個數。

  • 將初始計數設定為0。

  • 使用while迴圈實現二分查詢,其中start=1,end=num。

  • 計算中間數為temp=(start+end)/2。

  • 如果temp與其數字之和的差值不小於L,則所有大於temp的數字也滿足相同條件。

  • 包括temp在內的此類數字的個數為num-temp+1。將其新增到計數中。並將end設定為temp-1。

  • 否則,將start設定為temp+1。

  • 在二分查詢結束時,count將包含數字與其數字之和的差值不小於L的數字個數。

  • 返回count作為結果。

示例

 線上演示

#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
int Digit_sum(LL num){
   LL total = 0;
   while (num > 0){
      total += num % 10;
      num = num/10;
      z}
   return total;
}
LL Less_than_L(LL num, LL L){
   LL count = 0;
   LL start = 1;
   LL end = num;
   while (start <= end){
      LL temp = (end + start) / 2;
      LL temp_2 = temp - Digit_sum(temp);
      if (temp_2 >= L){
         count = num - temp + 1;
         end = temp - 1;
      }
      else{
         start = temp + 1;
      }
   }
   return count;
}
int main(){
   LL num = 234516;
   LL L = 235;
   cout<<"Count of Numbers such that difference between the number and sum of its digits not
   less than L are: "<< Less_than_L(num, L);
   return 0;
}

輸出

如果執行以上程式碼,將生成以下輸出:

Count of Numbers such that difference between the number and sum of its digits not less than L are: 234267

更新於:2020年12月3日

78 次瀏覽

開啟你的職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.