C++中計算其與反轉數之差為k的倍數的數字
給定一個範圍[l,r]和一個數字k。目標是在l和r之間找到所有數字(l<=number<=r),使得(該數字的反轉數)-(該數字)的結果是k的倍數。
我們將從l到r開始檢查這個條件,計算每個數字的反轉數。現在從其反轉數中減去該數字,並檢查(絕對差)%k==0。如果是,則遞增計數。
讓我們透過示例來理解。
輸入 − L=21, R=25, K=6
輸出 − 數字計數 − 2
說明 −
The numbers their reverse and difference is: 21, 12, | 21-12 |=9, 9%6!=0 22, 22, | 22-22 |=0 0%6=0 count=1 23,32, | 32-23 | =9 9%6!=0 24,42, | 42-24 | =18 18%6=0 count=2 25,52, | 52-25 | =27 27%6!=0 Total numbers that meet the condition are 2 ( 22,24 )
輸入 − L=11, R=15, K=5
輸出 − 數字計數 − 1
說明 −
The only number is 11 , | 11-11 | is 0 and 0%5=0
下面程式中使用的方法如下
我們取整數L和R來定義範圍。以及K用於檢查可整除性。
函式countNumbers(int l, int r, int k)以l、r和k作為輸入,並返回滿足所需條件的數字個數。
將初始計數設為0。
取數字的反轉數rev=0。
取餘數rem=0。
從i=l到i=r開始。
將當前數字i儲存在num中,其rev=0。
現在反轉數字num,while(num>0)。rem=num%10. rev=rev*10+rem. num=num/10。
while迴圈結束後,rev包含i的反轉數。
計算rev和原始值i的絕對差。如果這個差| i-rev |%k==0。然後遞增計數。
對範圍內的所有數字執行此操作。
返回count的最終值作為其與反轉數之差為k的倍數的數字。
示例
#include <iostream>
using namespace std;
int countNumbers(int l, int r, int k){
int rev = 0;
int count=0;
int rem=0;
for (int i = l; i <= r; i++){
int num=i;
rev=0;
while (num > 0){
// reverse the number
rem=num%10;
rev = rev * 10 + rem;
num /= 10;
}
if((abs(i-rev))%k==0) //original number is i and its reverse is rev
{ count++; }
}
return count;
}
int main(){
int L= 18, R = 24, K = 6;
cout <<" Numbers whose difference with reverse is product of k:"<<countNumbers(L,R,K);
return 0;
}輸出
如果我們執行上面的程式碼,它將生成以下輸出:
Numbers whose difference with reverse is product of k:4
廣告
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP