您的位置:首页 > 其它

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

2016-09-29 11:11 459 查看
华电北风吹

天津大学认知计算与应用重点实验室

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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: