leetcode 660. Remove 9

Start from integer 1, remove any integer that contains 9 such as 9, 19, 29...

So now, you will have a new integer sequence: 1, 2, 3, 4, 5, 6, 7, 8, 10, 11, ...

Given a positive integer n, you need to return the n-th integer after removing. Note that 1 will be the first integer.

Example 1:

Input: 9
Output: 10

 

Hint: n will not exceed 9 x 10^8.

首先预处理出 i 位数多出来多少,比如n是1位数,那么就多出1,n是两位数那么就多出19。

然后对于题目中的n  比如 n = 109,我们首先判断他在增加后是几位数,109 > 9     ,  109 > 100 - 19 ,109 < 1000 - 271  所以n是三位数,那么相应的ans就加上100,然后处理剩下的n(这时的n不是n-100而是n-100 + 19)。

集体看代码吧,这不好描述。。。。

class Solution {
public:
    typedef long long ll;
    ll sum[11] = {0};
    ll d[11] = {0};
    void init() {
        int x = 1;
        sum [1] = 1;
        d[1] = 1;
        for (int i = 2; i <= 10; ++i) {
            d[i] = sum[i - 1] * 8 + (ll)pow(10.0,i-1);
            sum[i] = sum[i - 1] + d[i];
        }
    }
    int newInteger(int n) {
        init();
        ll x = 10,ans = 0;
        while (n > 9) {
            ll tmp = n;
            x = 0;
            for (int i = 1; i <= 10; ++i) {
                if (n  >= pow(10,i) - sum[i]) continue;
                else {
                    x = i;break;
                }
            }
            n -= pow(10.0, x - 1);
            n += sum[x - 1];
            ans += pow(10.0, x - 1);
        }
        if (n == 9) ans ++;
        return ans + n;
    }
};

看到网上也有把10进制转换到9进制去搞的。。http://www.cnblogs.com/pk28/p/7356218.html

posted on 2017-08-14 09:54  Beserious  阅读(247)  评论(0编辑  收藏  举报