什么是解决这个编程挑战的最佳算法?给定一个由数字6和9组成的正整数。

huangapple go评论79阅读模式
英文:

what is the best algorithm to solve this programming challenge ? Given a positive integer number consisting only of digits 6 and 9

问题

给定一个仅由数字6和9组成的正整数num。

将最多一个数字更改为最大数(6变为9,9变为6),返回你可以得到的最大数字。

示例1:

输入:num = 9669
输出:9969
解释:
将第一个数字更改为得到6669。
将第二个数字更改为得到9969。
将第三个数字更改为得到9699。
将第四个数字更改为得到9666。
最大数字为9969。

示例2:

输入:num = 9996
输出:9999
解释:将最后一个数字6更改为9,得到最大数字。

示例3:

输入:num = 9999
输出:9999
解释:最好不进行任何更改。
英文:

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.

答案1

得分: 2

以下是翻译好的代码部分:

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class testing {
    public static void main(String[] args) throws FileNotFoundException {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter a number : ");
        int a = sc.nextInt();
        String numberString = Integer.toString(a);

        for (int i = 0; i < numberString.length(); i++) {
            char c = numberString.charAt(i);
            if (c == '6') { // 检查数字是否为 6,如果是 6,则将其改为 9
                numberString = numberString.substring(0, i) + '9' + numberString.substring(i + 1);
                break; // 如果 6 被改为 9,则中断循环
            }
        }
        System.out.println("Largest Number is : " + numberString);
    }
}
英文:

Traverse from left to right and change the first occurrence of 6 to 9. If there is not any 6 while traversal then does not change any digit.
Following code may help:-

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class testing {
    public static void main(String[] args) throws FileNotFoundException {
        Scanner sc=new Scanner(System.in);
        System.out.print(&quot;Enter a number : &quot;);
        int a=sc.nextInt();
        String numberString = Integer.toString(a);

        for (int i = 0; i &lt; numberString.length(); i++){
            char c = numberString.charAt(i);
            if(c==&#39;6&#39;) { // check if the digit is 6 or not, if 6 is present then change it to 9
                numberString = numberString.substring(0, i) + &#39;9&#39; + numberString.substring(i + 1);
                break; // break the loop if 6 is changed to 9
            }
        }
        System.out.println(&quot;Largest Number is : &quot;+numberString);
    }


}

答案2

得分: 1

public class Maximum69 {
    public static void main(String[] args) {
        int num = 6669;
        int added = 0;
        int cur = 1;
        int curNum = num;
        while (curNum > 0) {
            if (curNum % 10 == 6)
                added = cur;
            cur *= 10;
            curNum = curNum / 10;
        }
        System.out.println(num + added * 3);
    }
}

我找到了解决方法这个运行时间更短
英文:
public class Maximum69 {
public static void main(String[] args) {
    int num=6669;
        int added = 0;
        int cur = 1;
        int curNum = num;
        while(curNum &gt; 0) {
            if(curNum % 10 == 6)
                added = cur;
            cur *= 10;
            curNum = curNum / 10;
        }
       System.out.println(num + added * 3);

}

}

I found out how to slove, This takes less time to run:

答案3

得分: 1

我找到了一个公式,它本可以是一行代码的解决方案,但为了清晰起见,我分成了两行:

  • 首先,根据输入数字的位数,获取最高数字,例如如果输入是6,topNumber 将为9,对于69,top 将为99,对于696,top 为999,因此 topNumber 可以是 999999999999999,等等,直到 Java 限制,计算整数位数的公式为:
    floor(log10(input)) + 1
  • 然后你可以注意到,最高数字减去输入数字,得到一个以3开头的数字,例如 9-6 = 3,99 - 69 = 30,999 - 696 = 303,除非输入等于最高数字,在这种情况下结果为0,
  • 根据这个事实,我们可以得出结论,要切换数字中的第一个6可以通过累加 3 * (((6的位置) -1) * 10) 来实现,例如 330300300030000,等等。
  • 函数的最后部分结果为:input + (10^(NumberOfDigits(top - input)) -1) * 3
private static int largest69(int number) {	
		int topNumber = (int) (Math.pow(10,(int)(Math.log10(number)) + 1) -1);
        return  number + (int) Math.pow(10,(( (int)(Math.log10(topNumber - number)) + 1 ) -1) ) * 3;		
	}
英文:

I have found a formule, it could have been a single line solution but for clarity I have divided in two lines

  • First , get the highest number based on input number of digits , for example if input is 6, topNumber will be 9, for 69 top will be 99 , for 696 top is 999, so topNumber can be 9 or 99 or 999 or 9999 or 99999,etc up to java limit, the formula to get number of digits in an integer is :
    floor(log10(input)) + 1
  • Then you can notice that the top number minus the input, it gives you a number that starts with 3, for example 9-6 = 3 , 99 - 69 = 30 , 999 - 696 = 303, except when the input is equal to the top number, in that case the result is 0,
  • knowing that fact, we can conclude that for switching the first 6 in the number can be achieved by summing up 3 * (((the position of the 6) -1) * 10) , eg. 3 or 30 or 300 or 3000 or 30000, etc.
  • resulting in the last part of the function : input + (10^(NumberOfDigits(top - input)) -1) * 3
private static int largest69(int number) {	
		int topNumber = (int) (Math.pow(10,(int)(Math.log10(number)) + 1) -1);
        return  number + (int) Math.pow(10,(( (int)(Math.log10(topNumber - number)) + 1 ) -1) ) * 3;		
	}

答案4

得分: 0

如果你不像nitinsridar那样在直观地将数学应用到算法中,或者如果你不想像backdoor那样处理字符串,那么你可以利用数据结构帮助你轻松找到解决方案,无需过多思考。

public static void main(String[] args) {
    System.out.println(maxNumber(9669));
}

public static int maxNumber(int number) {
    Stack<Integer> numbers = new Stack<Integer>();
    
    int numberLength = 0;
    while(number > 0) {
        numbers.push(number % 10);
        number /= 10;
        numberLength++;
    }
    
    boolean changedFirstOccurrence = false;
    int maxNumber = 0;
    for(int i = numberLength; i > 0; i--) {
        int numberToAdd = numbers.pop();
        if (numberToAdd == 6 && !changedFirstOccurrence) {
            numberToAdd = 9;
            changedFirstOccurrence = true;
        }
        maxNumber += numberToAdd * (int) Math.pow(10, i);
    }
    return maxNumber / 10;
}

这是最佳解决方案吗?不是的,我会选择nitinsridar的答案(我也认为他/她的答案应该获得勾选标记)。

在我上数据结构和算法课之前,backdoor的答案绝对是我解决这个问题的方式。我并不是在说这是一个不好的答案。事实上,他的算法比我的更简洁。只是我的观点是,你不应该养成依赖字符串操作来解决这些“数字”问题的习惯,因为总有一天它不会起作用;在这种情况下,它起作用了。我只是提供了另一种做法。

英文:

If you're not as good as nitinsridar at intuitively implementing math into your algorithm, and if you don't want to mess around with strings like backdoor did, then you can utilize data structures to help you come to a solution without much thought

public static void main(String[] args) {
	System.out.println(maxNumber(9669));
}

public static int maxNumber(int number) {
	Stack&lt;Integer&gt; numbers = new Stack&lt;Integer&gt;();
	
	int numberLength = 0;
	while(number &gt; 0) {
		numbers.push(number % 10);
		number /= 10;
		numberLength++;
	}
	
	boolean changedFirstOccurrence = false;
	int maxNumber = 0;
	for(int i = numberLength; i &gt; 0; i--) {
		int numberToAdd = numbers.pop();
		if (numberToAdd == 6 &amp;&amp; !changedFirstOccurrence) {
			numberToAdd = 9;
			changedFirstOccurrence = true;
		}
		maxNumber += numberToAdd * (int) Math.pow(10, i);
	}
	return maxNumber / 10;
}

Is this the best solution? Nope, I would go with nitinsridar's answer (I also believe that his/her answer should get the green checkmark).

Backdoor's answer is definitely how I would've solved this problem before I took my data structures and algorithms class. I'm not saying it's a bad answer. In fact, his algorithm is more concise than mine. It's just my opinion that you don't want to get in the habit of relying on string manipulation to solve these sort of "numerical" problems, because one day it's not going to work; in this case, it did. I'm just providing another way of doing it

huangapple
  • 本文由 发表于 2020年4月4日 13:08:00
  • 转载请务必保留本文链接:https://go.coder-hub.com/61024033.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定