2017-11-25 165 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; 
} 

这个代码我的意见中提到本身的解释,它可能不适用于所有的测试用例工作,剩下的自己尝试。