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个回文数的前一半,然后将其补全就可以了。
代码详解:
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; } };
相关文章推荐
- Sum of first K even-length Palindrome numbers-LintCode
- Sum of first K even-length Palindrome numbers
- LintCode 744. Sum of first K even-length Palindrome numbers
- UVA 1210(p343)----Sum of Consecutive Prime Numbers
- POJ 2739 Sum of Consecutive Prime Numbers
- POJ 2739 Sum of Consecutive Prime Numbers(素数表)
- Sum of Consecutive Prime Numbers UVA - 1210 连续素数之和
- 【寒江雪】C. Given Length and Sum of Digits
- POJ 2739 Sum of Consecutive Prime Numbers
- POJ 2739 Sum of Consecutive Prime Numbers
- 2739 Sum of Consecutive Prime Numbers
- C - Sum of Consecutive Prime Numbers(1.2.2)
- Sum of Consecutive Prime Numbers
- (尺取法+素数打表)poj2739,Sum of Consecutive Prime Numbers
- UVa 1210 - Sum of Consecutive Prime Numbers
- UVa1210 - Sum of Consecutive Prime Numbers
- Sum of Consecutive Prime Numbers(POJ 2739)尺取法+数学问题
- Poj 2739 Sum of Consecutive Prime Numbers
- leetcode[Sum of Square Numbers]
- POJ2739 Sum of Consecutive Prime Numbers