forked from JGEC-Winter-of-Code/JWoC_Algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
/
palincount.cpp
57 lines (46 loc) · 896 Bytes
/
palincount.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
// C++ program for the
// above approach
#include <bits/stdc++.h>
using namespace std;
// Function to check
// palindrome
bool isPalindrome(string& s)
{
int left = 0, right = s.size() - 1;
while (left <= right) {
if (s[left] != s[right]) {
return false;
}
left++;
right--;
}
return true;
}
// Function to calculate
// the sum of n-digit
// palindrome
long long getSum(int n)
{
int start = pow(10, n - 1);
int end = pow(10, n) - 1;
long long sum = 0;
// Run a loop to check
// all possible palindrome
for (int i = start; i <= end; i++) {
string s = to_string(i);
// If palndrome
// append sum
if (isPalindrome(s)) {
sum += i;
}
}
return sum;
}
// Driver code
int main()
{
int n = 1;
long long ans = getSum(n);
cout << ans << '\n';
return 0;
}