You got a box with a combination lock. The lock has a display showing n digits. There are two buttons on the box, each button changes digits on the display. You have quickly discovered that the first button adds 1 to all the digits (all digits 9 become digits 0), and the second button shifts all the digits on the display one position to the right (the last digit becomes the first one). For example, if the display is currently showing number 579, then if we push the first button, the display will show 680, and if after that we push the second button, the display will show 068.
You know that the lock will open if the display is showing the smallest possible number that can be obtained by pushing the buttons in some order. The leading zeros are ignored while comparing numbers. Now your task is to find the desired number.
The first line contains a single integer n (1 ≤ n ≤ 1000) — the number of digits on the display.
The second line contains n digits — the initial state of the display.
Print a single line containing n digits — the desired state of the display containing the smallest possible number.
3 579
024
4 2014
0142
题意:
将输入的数据看作一串数字字符串而不是一个整数,按钮一作用为字符串中每个数字+1,若为9则变为0
按钮二作用为整体右移一格,最后一位数字变为第一位数字
通过按数次按钮一和二,将字符串变化为当作整数看待时数字最小的字符串,输出该最小字符串。
找规律:
579->680->068-> ①
179->280->028-> ②
139->240->024-> ③ (此处一次性+6)
680->循环
3位数字579 变换为以0为首位时共有三种可能,同理可推例二2014变换为以0为首位时有四种可能
n位数字有n种可能
对n种可能用strcmp()进行比较,得到最小值即答案。
A.
#include<algorithm>
#include<cstdio>
#include<iostream>
#include<cstring>
#include<string.h>
#include<cmath>
using namespace std;//
void button_one_all(char *line,int n);
void button_two(char *line,int n);
int main()
{
int n;//找规律,最后一位为零时n位数有n种可能,比较找出最小
scanf("%d",&n);
char line[n+5];//save字符串在被换成最小字符串之前为缓冲作用
memset(line,0,sizeof(line));
scanf("%s",line);
char save[n+5];
memset(save,0,sizeof(save));
strcpy(save,line);
//printf("%d\n%s\n%s\n",n,line,save);
/*char line[4]="068";
button_one_all(line,3);
printf("%s",line);*/
for(int i=0;i<n*2;i++)
{
if(line[n-1]=='0')button_two(line,n);
else button_one_all(line,n);
if(strcmp(save,line)>0)strcpy(save,line);
}
printf("%s\n",save);
}
void button_two(char *line,int n)//运行一次,等于按下一次按钮二,右移一位
{
int i;
char s=line[n-1];
for(i=n-1;i>=1;i--)
line[i]=line[i-1];
line[0]=s;
//printf("%s\n",line);
return;
}
void button_one_all(char *line,int n)//模拟按钮一功能不过是函数运行一次等于多次按下按钮一直至最后一位清零
{
int i;
int s=58-line[n-1];
for(i=0;i<n-1;i++)
{
line[i]+=s;
if(line[i]>57){
line[i]=47+line[i]%57;
}
}
line[n-1]='0';
//printf("%s\n",line);
return;
}
/*所用函数 strcpy(a,b),strcmp(a,b) a,b为字符串指针,注意strcmp的返回值有三种
注意点:
1.将函数分块处理,封装函数,用数据测试,保证单个函数功能正确
2.0的ASCII码为48*/