【问题标题】:Digital Sum and Sort Implementation数字求和和排序实现
【发布时间】:2016-05-06 20:36:40
【问题描述】:

我得到一个 = [13, 20, 7, 4] 整数数组,我正在尝试编写如图所示的 digitalsumandsort(a) = [20, 4, 13, 7] 函数。如果两个数字具有相同的数字总和,则较小的数字(在常规意义上)应该排在第一位。 4 和 13 具有相同的数字总和,但是 4

std::vector<int> digitalsumandsort(std::vector<int> a) {
    std::vector<int> result;
    int sum=0;
    int max=999;
    int temp;
    for (int i=0; i<a.size();i++){
        temp=a[i];
        while(temp>0){
            sum+=temp%10;
            temp/=10;
        }
        result.push_back(sum);
        sum=0;    
    }
    std::sort(result.begin(),result.begin()+4);
    return result;
}

输入: 答:[13、20、7、4] 输出: [2、4、4、7] 预期输出: [20、4、13、7]

【问题讨论】:

  • 你排序并返回resultresult 包含总和。您想要收集总和,根据总和对a 进行排序并返回排序后的a。考虑一个vector&lt;pair&lt;int,int&gt;,它包含数字和和源编号对,或者指定一个自定义比较器来动态计算数字和,然后根据数字和对源编号进行排序。

标签: c++ algorithm sorting c++11 data-structures


【解决方案1】:

您需要为排序函数提供自定义比较器。

std::vector<int> initial_values = {13, 20, 4, 7};
std::vector<int> sorted_values = initial_values;
std::sort(sorted_values.begin(), sorted_values.end(), [](const int & a, const int & b) {
    int a_temp = a, b_temp = b;
    int a_sum = 0, b_sum = 0;
    while(a_temp != 0) {
        a_sum += a_temp % 10;
        a_temp /= 10;
    }
    while(b_temp != 0) {
        b_sum += b_temp % 10;
        b_temp /= 10;
    }
    if(a_sum != b_sum) return a_sum < b_sum;
    else return a <= b;
});

print_contents_of_vector(initial_values);
print_contents_of_vector(sorted_values);

输出:

{13, 20, 4, 7} //From initial value printing
{20, 4, 13, 7} //From sorted value printing

【讨论】:

  • 非常感谢@Xirema
【解决方案2】:

您可以这样做。使用比较器进行排序功能,如下所示。这是link

#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;

int sum_digits(int a ) {
    int sum=0;
    while(a!=0) {
        sum += a%10;
        a /= 10;
    }
    return sum;
}

struct Comparator {
    bool operator()(int a, int b) {
        int sum_digits_a = sum_digits(a);
        int sum_digits_b = sum_digits(b);

        if(sum_digits_a == sum_digits_b)
            return a < b;
        return sum_digits_a < sum_digits_b;
    }
};

int main() {
    vector<int> vec{13, 20, 7, 4};  
    sort(vec.begin(), vec.end(), Comparator() );

    for(auto v : vec)
        cout << v << " ";
    return 0;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-09
    • 1970-01-01
    • 1970-01-01
    • 2013-01-13
    • 2010-09-22
    • 2013-03-10
    相关资源
    最近更新 更多