LeetCode //C - 1323. Maximum 69 Number

1323. Maximum 69 Number

You are 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).

Example 1:

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.

Example 2:

Input: num = 9996

Output: 9999

Explanation: Changing the last digit 6 to 9 results in the maximum number.

Example 3:

Input: num = 9999

Output: 9999

Explanation: It is better not to apply any change.

Constraints:
  • 1 < = n u m < = 10 4 1 <= num <= 10^4 1<=num<=104
  • num consists of only 6 and 9 digits.

From: LeetCode

Link: 1323. Maximum 69 Number


Solution:

Ideas:

To maximize the number, change the leftmost 6 into 9.

The loop processes digits from right to left. Whenever it finds a 6, it records that digit's place value. The last recorded position is therefore the leftmost 6.

Changing 6 to 9 increases that digit by 3, so we add:

3 * place

For 9669, the leftmost 6 is in the hundreds place:

9669 + 3 × 100 = 9969

Code:
c 复制代码
int maximum69Number(int num) {
    int place = 1;
    int rightmostSixPlace = 0;
    int temp = num;

    while (temp > 0) {
        if (temp % 10 == 6) {
            rightmostSixPlace = place;
        }

        temp /= 10;
        place *= 10;
    }

    if (rightmostSixPlace > 0) {
        num += 3 * rightmostSixPlace;
    }

    return num;
}
相关推荐
geovindu1 小时前
python:Lasso
开发语言·后端·python·算法
AAA修煤气灶刘哥2 小时前
同一个模型,为什么还要专门练一遍怎么用工具?
人工智能·后端·算法
Severus_black2 小时前
【C++初阶】模板进阶
c语言·c++·学习
AAA修煤气灶刘哥2 小时前
两个 Agent 各自改得都对,合在一起为什么出错?
人工智能·后端·算法
旖旎夜光3 小时前
【C 语言】(一)(下)指针进阶:const、二级指针、函数指针与指针题
c语言·开发语言·笔记·学习
电科_银尘3 小时前
【大模型算法与工程 34】QLoRA:量化底座上的低秩训练
人工智能·算法·机器学习
专注仿真3 小时前
智能体训练:模仿学习与 MCTS 算法详解与实战
算法·强化学习·仿真·afsim智能体·仿真训练
旖旎夜光4 小时前
【C 语言】(一)(上)认识指针:内存、指针类型与指针进阶
c语言·开发语言·笔记·学习
是main不是漫14 小时前
【快慢指针 | LeetCode202 快乐数】鸽巢原理佐证环特性,快慢指针巧解快乐数
c语言·开发语言·c++·算法