【POJ 2719 --- Faulty Odometer】
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 3 to the digit 5, always skipping over the digit 4. This defect shows up in all positions (the one’s, the ten’s, the hundred’s, etc.). For example, if the odometer displays 15339 and the car travels one mile, odometer reading changes to 15350 (instead of 15340).
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 4.
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
13
15
2003
2005
239
250
1399
1500
999999
0
Sample Output
13: 12
15: 13
2003: 1461
2005: 1462
239: 197
250: 198
1399: 1052
1500: 1053
999999: 531440
- 解题思路
遇见4则直接跳到5,那么我们可以理解为这个题中数字的自增方式为1,2,3,5,6,7,8,9,0;那么我们是否可以看成1,2,3,4,5,6,7,8,0只不过是后面大于4的全部减一而已。
看到1,2,3,4,5,6,7,8,0仔细一想这不是9进制的自增方式吗,本题数据在自增的过程中缺少一个4那就相当与是九进制转换为十进制。只不过需要考虑每位数字是否大于4,大于4的需要减1;
AC代码:
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
using namespace std;
int fun(long long n)
{
long long sum=0;
int y=1;
while(n)
{
int x = n%10;
if(x>4)
x--;
sum+=x*y;
y*=9;
n/=10;
}
return sum;
}
int main()
{
long long x;
while(cin >> x && x)
{
cout << x << ": " << fun(x) << endl;
}
return 0;
}