Palindromic Ranges-LintCode

204 篇文章 0 订阅

A positive integer is a palindrome if its decimal representation (without leading zeros) is a palindromic string (a string that reads the same forwards and backwards). For example, the numbers 5, 77, 363, 4884, 11111, 12121 and 349943 are palindromes.

A range of integers is interesting if it contains an even number of palindromes. The range [L, R], with L <= R, is defined as the sequence of integers from L to R (inclusive): (L, L+1, L+2, …, R-1, R). L and R are the range’s first and last numbers.

The range [L1, R1] is a subrange of [L, R] if L <= L1 <= R1 <= R. Your job is to determine how many interesting subranges of [L, R] there are.

样例:
Given L = 1, R = 2, return 1
Given L = 1, R = 7, return 12
Given L = 87, R = 88, return 1

思路:
题目的意思是计算包含偶数个回文数字的子区间的个数。
例如L=8,R=11
8,9,10, 11
构建数组v,判断是否为回文数字,得到{1,1,0,1}
接下来寻找包含的数字之和为偶数的子区间
即为:{0},{1,1},{1,1,0},{1,0,1}

#ifndef C745_H
#define C745_H
#include<iostream>
#include<string>
#include<vector>
using namespace std;
class Solution {
public:
    /**
    * @param L: A positive integer
    * @param R: A positive integer
    * @return: the number of interesting subranges of [L, R]
    */
    //计算包含偶数个回文数字的子区间的个数
    int PalindromicRanges(int L, int R) {
        // Write your code here
        string res;
        int range = R - L + 1;
        int cnt = 0;
        vector<int> v;//构建数组表示每个数字是否是回文数字
        for (int i = L; i <= R; ++i)
        {
            if (isPalindorme(to_string(i)))
                v.push_back(1);
            else
            {
                v.push_back(0);
                cnt++;
            }
        }
        for (int j = 1; j < range; ++j)
        {
            int num = v[j - 1];
            for (int k = j; k <range; ++k)
            {
                num += v[k];
                if (num % 2 == 0)
                    cnt++;
            }
        }
        return cnt;
    }
    //判断是否为回文串
    bool isPalindorme(string str)
    {
        if (str.empty())
            return true;
        int l = 0, r = str.size() - 1;
        while (l < r)
        {
            if (str[l] != str[r])
                return false;
            l++;
            r--;
        }
        return true;
    }
};
#endif
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值