lintcode---Sum of first K even-length Palindrome numbers

来源:互联网 发布:西甲球员数据统计 编辑:程序博客网 时间:2024/05/24 03:26

题目描述:
Given a integer k, find the sum of first k even-length palindrome numbers.
Even length here refers to the number of digits of a number is even.

样例:
Given k = 3, return 66
// 11 + 22 + 33 = 66 (Sum of first three even-length palindrome
numbers)

Given k = 10, return 1496
// 11 + 22 + 33 + 44 + 55 + 66 + 77 + 88 + 99 + 1001 = 1496

思路讲解:
一开始我的思路是按照递归的方法第一次是1-9,其他的每次往其后面添加0-9这些数字,然后再将其转化为回文数,最后发现不对,顺序不对,因为递归的话是一个递归到底,而不是一行一行的递归,后面我想到了一种方法就是因为是偶数长度,我们观察上面给出的样例,我们可以发现他们的一半是1-2-3以及1-2-3-4-5-6-7-8-9-10这样,最后一个数刚好是K,所以我就想到我们可以先得到这K个回文数的前一半,然后将其补全就可以了。

代码详解:

class Solution {public:    /**     * @param k:      * @return: the sum of first k even-length palindrome numbers     */    int sumKEven(int k) {        // Write your code here        int count=0;        vector<string>res;        for(int i=1;i<=k;i++)        {            string tmp=to_string(i);            res.push_back(getpalnum(tmp));        }        int sum=0;        for(int i=0;i<k;i++)//求和        {            cout<<res[i]<<endl;            sum=sum+stoi(res[i].c_str());        }        return sum;    }    string getpalnum(string tmp)//将一个字符串转化为回文字符串    {        string a=tmp;        reverse(a.begin(),a.end());        return tmp+a;    }};
原创粉丝点击