Get into the habit of writing together! This is the 21st day of my participation in the "Nuggets Daily New Plan · April Update Challenge", click to view the details of the event .
1. Problem description
Give you a positive integer consisting only of the numbers 6 and 9 num
.
You can flip at most one digit, turning a 6 into a 9, or a 9 into a 6.
Please return the highest number you can get.
Topic link: The largest number composed of 6 and 9
Second, the subject requirements
Sample
输入: num = 9669
输出: 9969
解释:
改变第一位数字可以得到 6669 。
改变第二位数字可以得到 9969 。
改变第三位数字可以得到 9699 。
改变第四位数字可以得到 9666 。
其中最大的数字是 9969 。
复制代码
visit
1.贪心模拟
2.建议用时10~25min
复制代码
3. Problem Analysis
This is a relatively simple greedy problem. The greedy algorithm is essentially a choice at each step 最好或者最优(即最有利)的选择
, hoping to lead to the best or optimal algorithm.
This problem requires us to flip at most one digit to get the maximum value.
Then we should first judge from the highest bit. If it is 6, then flip it to 9 and exit the result.
Below, the first one uses the most intuitive array method, and the second one uses some functions of C++.
Fourth, the encoding implementation
1. Basics
class Solution {
public:
int maximum69Number (int num) {
int i,k=0;
vector<int>v;
while(num)//每一位数字数组存储
{
v.push_back(num%10);
num=num/10;
}
for(i=v.size()-1;i>=0;i--)//从高位开始判断
{
if(v[i]==6)
{
v[i]=9;
break;
}
}
for(i=0;i<v.size();i++)//输出结果
k+=v[i]*pow(10,i);
return k;
}
};
复制代码
2. Advanced
class Solution {
public:
int maximum69Number (int num) {
string s=to_string(num);//数字转字符串
int i;
for(i=0;i<s.size();i++)
{
if(s[i]=='6')//高位判断
{
s[i]='9';
break;
}
}
return stoi(s);//字符串转数字
}
};
复制代码