Wednesday, May 15, 2013

Six digit number with equal sum C++

Write an algorithm to find the number of six digit numbers where the sum of the first three digits is equal to the sum of the last three digits.

思路:找总数太简单了,写个找所有满足条件的数的code吧。
3位数的数字之和最多27,0不用考虑,所以建一个size为27的bucket,遍历所有的三位数组合,按数字和分类放入bucket里面,这样要得到要求的6位数,只要前三位和后三位在同一个bucket就可以了。复杂度就是n^3+27*n^2~1000+2700~O(n^3), n=10. 这里用string来存每个整数,一个是节省空间,还有就是输出的code写起来方便,如果要把结果存入变量,只要append两个三位数的string就行了。

  1. void findall(){  
  2.   //set up an array, each element stores strings with sum = index of the element  
  3.   vector<string> digit3[27];   
  4.   
  5.   string str;  
  6.   //group 3-digit integers with equal sum into each array element  
  7.   for(int i = 0; i < 10; i++){  
  8.             
  9.     for(int j = 0; j < 10; j++){  
  10.   
  11.        for(int k = 0; k < 10; k++){  
  12.   
  13.           int sum = i + j + k;  
  14.   
  15.           if(sum > 0) {  
  16.             str.clear();  
  17.             str.push_back(i+'0');   
  18.             str.push_back(j+'0');  
  19.             str.push_back(k+'0');   
  20.   
  21.             digit3[sum-1].push_back(str);  
  22.          }  
  23.       }    
  24.     }  
  25.   }  
  26.   
  27.  //print out all 6-digit numbers  
  28.  for(int i = 0; i < 27; i++){  
  29.    //len is the number of 3-digit integers with sum = i  
  30.    int len = digit3[i].size();    
  31.   
  32.    for(int j =0; j < len; j++){  
  33.              
  34.       for(int k = 0; k < len; k++){  
  35.   
  36.            string str1 = digit3[i][j];  
  37.   
  38.            string str2 = digit3[i][k];  
  39.             
  40.            if(str1[0] != '0') cout<<str1<<str2<<endl;  
  41.   
  42.       }  
  43.    }  
  44. }  
  45. }  

No comments:

Post a Comment