Problem Statement(250)
????
給定一個正整數n. 你可以修改n的十進位表示中任意一位而得到另一個十進位表示的數,你修改後得到的新數需要嚴格小於n (這個新數可以有一些前置0).請返回按照上述要求修改後得到的數中最大的一個。
Definition
????
Class:
ChangeDigit
Method:
change
Parameters:
int
Returns:
int
Method signature:
int change(int n)
(be sure your method is public)
????
Constraints
-
n 一個1到1,000,000,000 之間正整數。
Examples
0)
????
123
Returns: 122
修改了其中一位以後, 我們可以得到如下一些小於n的數: 023, 103, 113, 120, 121, 和 122. 其中最大的數是 122。
1)
????
94040
Returns: 94030
2)
????
999999999
Returns: 999999998
3)
????
1000000000
Returns: 0
在這個範例中, 我們只有一種修改方案,即將首位的 '1' 替換成 '0' 以得到 "0000000000", 這是一個十進位表示的0 (有9個前置0)。
4)
????
4321000
Returns: 4320000
public class First {
public static void main(String[] args) {
First f=new First();
System.out.println(f.change(999999999));
}
public int change(int n) {
int bit = 0;
int p = 10;
int temp = n;
while (true) {
if (temp % 10 != 0) {
return n - (p/10);
}
temp /= 10;
p *= 10;
}
}
}