Faulty Odometer

今天上午看了一下榜,http://acmicpc.info/icpc2012/tjut_online.php,发现大家 a 题刷刷的过,于是自己也敲了一下,好久没有敲题,居然一次过了 sample,呵呵,不过后来跟同学讨论的时候,发现我那个暴力模拟的思路实在太弱智了,在同学的指点下改成了进制转换的思路,没有账号,所以没有的交,不过 sample 是过了

题目,附上 pdf,2012TianJinOnlineProblemSet

Description You are given a car odometer which displays the miles traveled as an integer. The odometer has a defect, however: it proceeds from the digit 2 to the digit 4 and from the digit 7 to the digit 9, always skipping over the digit 3 and 8. This defect shows up in all positions (the one’s, the ten’s, the hundred’s, etc.). For example, if the odometer displays 15229 and the car travels one mile, odometer reading changes to 15240 (instead of 15230). Input Each line of input contains a positive integer in the range 1..999999999 which represents an odometer reading. (Leading zeros will not appear in the input.) The end of input is indicated by a line containing a single 0. You may assume that no odometer reading will contain the digit 3 and 8. Output Each line of input will produce exactly one line of output, which will contain: the odometer reading from the input, a colon, one blank space, and the actual number of miles traveled by the car.

Sample Input 15 2005 250 1500 999999 0

Sample Output 15: 12 2005: 1028 250: 160 1500: 768 999999: 262143

代码

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main() {
	int x;
	while (scanf("%d", &x) && x!=0) {
		char str[15] = {0};
		itoa(x, str, 10);
		for (int i=0; i<strlen(str); i++) {
			if (str[i] >= '8') {
				str[i] -= 2;
				continue;
			}
			if (str[i] >= '3') {
				str[i] -= 1;
				continue;
			}
		}
		int ans = 0;
		for (char *p=str; *p != '\0'; p++) {
			ans = ans*8 + (*p-'0');
		}
		printf("%d: %dn", x, ans);
	}
	return 0;
}

输入输出

15
15: 12
2005
2005: 1028
250
250: 160
1500
1500: 768
999999
999999: 262143
0

===================================

2012-9-9 21:30:09 update oj 上开放了题目,http://acm.hdu.edu.cn/showproblem.php?pid=4278,于是交了一下,不能用 itoa,于是改成了这样,能够 ac

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main() {
	int x;
	while (scanf("%d", &x) && x!=0) {
		char str[15] = {0};
		sprintf(str, "%d", x);
		for (int i=0; i<strlen(str); i++) {
			if (str[i] >= '8') {
				str[i] -= 2;
				continue;
			}
			if (str[i] >= '3') {
				str[i] -= 1;
				continue;
			}
		}
		int ans = 0;
		for (char *p=str; *p != '\0'; p++) {
			ans = ans*8 + (*p-'0');
		}
		printf("%d: %dn", x, ans);
	}
	return 0;
}
使用 Hugo 构建
主题 StackJimmy 设计