力扣题:给你一个仅由数字 6 和 9 组成的正整数 num。你最多只能翻转一位数字,将 6 变成 9,或者把 9 变成 6 。请返回你可以得到的最大数字

该代码示例是一个C++程序,用于解决一个问题:在给定整数中找到第一个6并将其替换为9,以得到最大的可能数值。程序首先记录每一位数字,然后从高位开始处理,遇到的第一个6被改为9,从而最大化数字。changemax函数用于计算给定位数字的最大值。
摘要由CSDN通过智能技术生成

解题思路,用数字记录每一位的数字,然后从高位还原,遇见的第一个6改为9,再还原;

#include <stdio.h>
#include <stdlib.h>
int changemax(int x, int count);
int maximum69Number(int num);

int main(int argc, char const *argv[])
{
    int num = 99666;
    int max = maximum69Number(num);
    printf("%d\n", max);
    return 0;
}

int maximum69Number(int num)
{
    int num1 = num;
    int count = 0;
    int max = 0;
    int flag = 0;

    while (num1)
    {
        num1 = num1 / 10;
        count++;
    }

    int *data = (int *)malloc(sizeof(int) * count);

    int i = 0;
    while (num)
    {
        data[i] = num % 10;
        num = num / 10; //
        i++;
    }
    while (count)
    {
        if (data[count - 1] == 9)
        {
            max += changemax(data[count - 1], count - 1);

            count--;
            continue;
        }
        if (data[count - 1] == 6 && flag == 0)
        {
            data[count - 1] = 9;
            max += changemax(data[count - 1], count - 1);
            flag = 1;
            count--;
            continue;
        }
        max += changemax(data[count - 1], count - 1);
        count--;
    }
    free(data);
    return max;
}
int changemax(int x, int count)
{
    int max = x;
    while (count)
    {
        max = max * 10;
        count--;
    }
    return max;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值