您的位置:首页 > 其它

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

2017-12-22 16:22 225 查看
题目描述:

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;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: