runaround numbers 肯定不包含0,数字不重复
两个技巧
把一个int 型整数按数字存入 char 数组, 然后将char 数组 改变为int 数组——sprintf函数
sprintf(numstr, "%d", n);
size = strlen(numstr);
for(i = 0; i < size; i++) {
numdig[i] = numstr[i] - 48;
}
检验数字是否run around 时,注意每次检验开始的点index
//whether Runaround
int times = size;
int index = 0;
while(times) {
index = (index + numdig[index]) % size;
visited[index] = true;
times--;
}
for(j = 0; j < size; j++) {
if(!visited[j]) return false;
}
我的代码
/*
ID: wangxin12
PROG: runround
LANG: C++
*/
#include <iostream>
#include <fstream>
#include <vector>
#include <string.h>
#include <stack>
using namespace std;
int N;
bool isRunaround(int n);
int main() {
//input
ifstream fin("runround.in");
fin>>N;
fin.close();
//
int n = N + 1;
while(!isRunaround(n)) {
n++;
}
//bool n = isRunaround(147);
//Output
ofstream fout("runround.out");
fout<<n<<endl;
fout.close();
return 0;
}
bool isRunaround(int n) {
char numstr[10];
int numdig[10];
bool visited[10] = { false };
int size, i, j;
sprintf(numstr, "%d", n);
size = strlen(numstr);
for(i = 0; i < size; i++) {
numdig[i] = numstr[i] - 48;
}
//有重复数字不算
for(i = 0; i < size - 1; i++) {
for(j = i + 1; j < size; j++) {
if(numstr[i] == '0' || numstr[j] == '0' || numstr[i] == numstr[j]) return false;
}
}
//whether Runaround
int times = size;
int index = 0;
while(times) {
index = (index + numdig[index]) % size;
visited[index] = true;
times--;
}
for(j = 0; j < size; j++) {
if(!visited[j]) return false;
}
return true;
}