網易有道比賽第一題解法(java)

來源:互聯網
上載者:User

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;
  }

 }
}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.