[英]How to output the digits of a number as an integer, which the digits can exact divide the another number?
I have to output the digits of a number as an integer, which the digits of this number can exact divide another number with the function unsigned deldigits(unsigned num, unsigned short div)
For example, if num=1234; div=2
num=1234; div=2
,然后是數字1%2=1 (then i need the digit 1)
, 2%2=0(take out)
, 3%2=1 (then i need the digit 3)
, 4%2=0 (take out)
,因此 output 必須為13
作為 integer。
不允許使用循環、globe/static 變量、數組或指針(也不允許使用庫函數,但我先用它來測試)。 我嘗試使用另一個 function 來幫助取消僅通過遞歸處理所有功能。 中間的計算是正確的,但不知何故 output integer 不正確,我無法理解。
unsigned deldigits(unsigned num, unsigned short div)
{
if(num == 0) return 0;
int digit = num / (digitPower(num)/10);
int modulo = digit % div;
printf("ziffer: %d div: %d modulo: %d\n", digit, div, modulo);
if(digitPower(num) == 0)
return 0;
return (digit*10 + deldigits(num - digit*(digitPower(num)/10), div));
}
int digitPower(int n)
{
if(n == 0) return 1;
return 10*digitPower(n/10);
}
int main()
{
unsigned n = 1234;
unsigned short d = 2;
int z = deldigits(n, d);
printf("deldigits: %d\n", z);
return 0;
}
主要的function只是測試功能和output。 在這種情況下, output 必須是13
,但現在我得到了錯誤的 output 120
。 有人可以幫我嗎? 謝謝!
你把問題復雜化了。 您可以使用
num % 10
獲取數字的最后一位,然后檢查它是否可以被 div 整除。 如果是,您將其添加到您的答案中,並以 10 為基數,然后通過將 num 除以 10 來刪除您剛剛檢查的數字。然后重復直到沒有更多數字。 示例代碼:
int recursion(int num,int div,int base) {
int out = 0;
if(num) {
int digit = (num % 10);
printf("digit %i\n",digit);
if((digit % div) != 0) {
out += digit * base;
base *= 10;
}
out += recursion(num/10,div,base);
}
return out;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.