2017-11-25 206 views
-2

我必須用C語言編寫一個程序來總和整數中的所有數字。我知道如何去做,如果我想總結數字。但問題是,我只需要總結不同的數字。
例如:122中有兩個2,所以我必須將它們加總爲1 + 2。你能幫我嗎?在C語言編程中總結不同的數字

+1

定義10個布爾值/整數的插槽,當您已經遇到該數字時將其設置爲True。現在很簡單,你可以自己做。 –

+0

您可以使用一個數組來存儲數字是否存在於給定的數字中,而不管頻率如何。然後再總結數字中的所有數字 –

回答

0

首先,你應該在這裏放一些代碼,無論你嘗試什麼,給你解決你的問題的基本想法,我在下面放置簡單的代碼。

#include<stdio.h> 
#include<malloc.h> 
int main() 
{ 
     int input, digit, temp, sum = 0; 
     printf("Enter Input Number :\n"); 
     scanf("%d",&input); 
     temp = input; 
     //first find how many digits are there 
     for(digit = 0 ; temp != 0 ;digit++, temp /= 10); 
     //create one array equal to no of digits, use dynamic array because once you find different digits you can re-allocate memory and save some memory 
     int *p = malloc(digit * sizeof(int)); 

     //now store all the digits in dynamic array 
     p[0] = input % 10;//1 
     for(int i = 0; i < digit ;i++) { 
       input /= 10; 
       p[i+1] = input %10; 
       if(p[i] != p[i+1]) 
         sum = sum + p[i]; 
     } 

     printf("sum of different digits : = %d \n",sum); 

     free(p); 
     p = 0; 

     return 0; 
} 

這個代碼我的意見中提到本身的解釋,它可能不適用於所有的測試用例工作,剩下的自己嘗試。