WY20 两种排序方法
链接:两种排序方法
题目:
考拉有n个字符串字符串,任意两个字符串长度都是不同的。考拉最近学习到有两种字符串的排序方法: 1.根据字符串的字典序排序。例如:
“car” < “carriage” < “cats” < "doggies < “koala”
2.根据字符串的长度排序。例如:
“car” < “cats” < “koala” < “doggies” < “carriage”
考拉想知道自己的这些字符串排列顺序是否满足这两种排序方法,考拉要忙着吃树叶,所以需要你来帮忙验证。
题目分析:
代码实现:
package Day8;import java.util.Scanner;public class Day8_1 {public static void main(String[] args) {Scanner scanner = new Scanner(System.in);while (scanner.hasNext()) {int n = scanner.nextInt();String[] str = new String[n];for (int i = 0; i < n; i++) {str[i] = scanner.next();}boolean len = isLensort(str);boolean dic = isDicsort(str);if(len && dic) {System.out.println("both");} else if (len) {System.out.println("lengths");} else if (dic) {System.out.println("lexicographically");}else {System.out.println("none");}}}public static boolean isLensort(String[] str) {for (int i = 0; i < str.length-1; i++) {if(str[i].length() > str[i+1].length()) {return false;}}return true;}public static boolean isDicsort(String[] str) {for (int i = 0; i < str.length-1; i++) {if (str[i].compareTo(str[i+1]) > 0) {return false;}}return true;}
}
HJ108 求最小公倍数
链接:求最小公倍数
题目:
正整数A和正整数B 的最小公倍数是指 能被A和B整除的最小的正整数值,设计一个算法,求输入A和B的最小公倍数。
题目分析:
代码实现:
package Day8;import java.util.Scanner;public class Day8_2 {public static void main(String[] args) {Scanner scanner = new Scanner(System.in);int m = scanner.nextInt();int n = scanner.nextInt();int mn = func(m,n);System.out.println((m * n) /mn);}public static int func(int m,int n) {if (m == n) {return m;}int k = 0;while ((k = m % n) > 0) {m = n;n = k;}return n;}
}