华电北风吹
天津大学认知计算与应用重点实验室
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;
}