【數學】C071_LC_6 和 9 組成的最大數字(思維很重要)

一、Problem

Given a positive integer num consisting only of digits 6 and 9.

Return the maximum number you can get by changing at most one digit (6 becomes 9, and 9 becomes 6).

Input: num = 9669
Output: 9969
Explanation: 
Changing the first digit results in 6669.
Changing the second digit results in 9969.
Changing the third digit results in 9699.
Changing the fourth digit results in 9666. 
The maximum number is 9969.

二、Solution

方法一:思維

  • 記錄最高位的數字 6 於變量 th 中,因爲最多隻能轉換一次。
  • 想一下將某一位的 6 變爲 9,那麼整個數字的價值提高了多少?
  • 很明顯是 3×10th3 × 10^{th}
class Solution {
    public int maximum69Number (int num) {
        int bit = 1, th = 0, x = num, d = 9 - 6;
        while (x > 0) {
            if (x % 10 == 6)
                th = bit;
            bit++;
            x /= 10;
        }
        return num + d * (int)Math.pow(10, th-1);
    }
}

複雜度分析

  • 時間複雜度:O(log10N)O(log_{10}N)
  • 空間複雜度:O(1)O(1)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章