[今日头条] 笔试题目2016/9/28

华电北风吹
天津大学认知计算与应用重点实验室
2016-09-29

String Shifting
字符串循环移位后有多少个跟原字符串相同。
解题思路:
当成字符串问题即可。KMP,BM等方法均可解决。

字典序:
题目描述:
给定整数n和m,将1到n的这n个整数按字典序排列之后,求其中的第m个数字。字典序排序规则和字符串排序规则一样。

参考代码:

#include <iostream>
#include <string>
#include <sstream>
#include <string.h>
#include <math.h>
using namespace std;

int result[20];

int CountBit(int n)
{
    int result = 0;
    while (n)
    {
        n /= 10;
        result++;
    }
    return result;
}

int MaxBitNum(int n)
{
    return n / pow(10, CountBit(n) - 1);
}

string Int2String(int n)
{
    stringstream ss;
    string s;
    ss << n;
    ss >> s;
    return s;
}

string OutLengthNum(int x, int k)
{
    string s = "";
    while (x)
    {
        s = Int2String(x % 10) + s;
        x /= 10;
    }
    while (s.length()<k)
    {
        s = '0' + s;
    }
    return s;
}

void func(int n, int m)
{
    int countNum = 0;
    int bitLength = CountBit(n);
    int maxBit = MaxBitNum(n);
    int i = 1, j = 1;
    for (; i < maxBit; i++)
    {
        for (j = 1; j <= bitLength; j++)
        {
            if (countNum + pow(10, j - 1) < m)
            {
                countNum += pow(10, j - 1);
            }
            else
            {
                cout << i;
                if (bitLength > 1)
                {
                    cout << OutLengthNum(m - countNum - 1, bitLength - 1);
                }
                cout << endl;
                return;
            }
        }
    }
    for (j = 1; j < bitLength; j++)
    {
        if (countNum + pow(10, j - 1) < m)
        {
            countNum += pow(10, j - 1);
        }
        else
        {
            cout << maxBit;
            if (j > 1)
            {
                cout << OutLengthNum(m - countNum - 1, bitLength - 1);
            }
            cout << endl;
            return;
        }
    }
    for (int temp = n / 10 * 10; temp <= n; temp++)
    {
        countNum++;
        if (countNum == m)
        {
            cout << temp << endl;
            return;
        }
    }
    for (i = maxBit + 1; i <= 9; i++)
    {
        for (j = 1; j < bitLength; j++)
        {
            if (countNum + pow(10, j - 1) < m)
            {
                countNum += pow(10, j - 1);
            }
            else
            {
                cout << i;
                if (j > 1)
                {
                    cout << OutLengthNum(m - countNum - 1, bitLength - 1);
                }
                cout << endl;
                return;
            }
        }
    }
}

int main()
{
    memset(result, 0, sizeof(result));
    int n, m;
    while(cin >> n >> m)
        func(n, m);
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值