Type 69 is a kind of… Cough, 69 problem is a very interesting algorithm. Well, you have to argue.
01. Examples of topics
Note that each digit in num is either 6 or 9.
Title: The largest number of 1323.6 and 9 |
---|
You are given a positive integer consisting only of the numbers 6 and 9num . |
It goes something like this:
Enter num = 9669Output: 9969
Explanation:Change the first digit to get 6669.Change the second digit to get 9969.Change the third digit to get 9699.Change the fourth digit to get 9666.The largest number is 9969.Copy the code
02, Solution analysis
Because the question is too easy, so… I don’t know why I brought it up. Anyway, it is not a collection of words 😂 (I will not tell you that I choose it because of the title dirt)
We can find the answer simply by finding the highest 6 in num and flipping it to 9.
//java
class Solution {
public int maximum69Number (int num) {
String s = num + "";
s = s.replaceFirst("6"."9");
return Integer.valueOf(s); } } Copy the code
Execution Result:
Emmmmm, something like that… I feel like I’m getting hammered, slipping away.
03, knowledge summary
Write the above answers. Chances are the interviewer has hammered them. So what is this question about?
As you can see, this is a math problem. So we need to solve it mathematically. The specific code is as follows:
//java
class Solution {
public int maximum69Number(int num) {
if (num / 1000= =6) {
num += 3000;
} else if (num % 1000 / 100= =6) { num += 300; } else if (num % 100 / 10= =6) { num += 30; } else if (num % 10= =6) { num += 3; } return num; } } Copy the code
And this solution, in fact, is no different from the solution above. They judge from the highest to the lowest, and when they hit a six they change it to a nine. However, this is done by replaceFirst, and this is done by adding values. Let’s look at the efficiency of this method:
There’s no hanging sky! No wonder the ancients said that if you learn math, physics and chemistry well, you can travel anywhere in the world. Can only replace painting, after the interview to find mom.
Now you know why you went to an interview with someone else and the interviewer passed you over in favor of someone else. The interviewer’s thinking is often so unpretentious and boring.
That’s the end of today’s topic, have you learned? Leave your thoughts in the comments section!
I’ve compiled all the problems I’ve written into an e-book, complete with illustrations for each problem. Click to download