文章目录
题目一
1.题目
题目链接:两种排序方法
2.思路
看别人的思路很简单的系列:
- 写两个方法,方法一是字典序判断,这里的注意事项是两个字符串使用字典序进行判断,需要使用的是compareTo,而不能是><=这类符号。方法二长度判断,直接遍历数组,判断前一个字符的长度与后一个字符的长度谁长谁短即可。
3.代码实现
import java.util.*;
public class Main{
public static void main(String[]args){
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
String str[] = new String[n+1];
for(int i =0; i<=n;i++){
str[i] = sc.nextLine();
}
boolean zd = iszd(str);
boolean cd = iscd(str);
if(zd && cd){
System.out.println("both");
}else if(zd){
System.out.println("lexicographically");
}else if(cd){
System.out.println("lengths");
}else{
System.out.println("none");
}
}
public static boolean iszd(String[] str){
//字符串使用字典排序进行判断比较实用 compareTo()
for(int i =0;i<str.length-1;i++){
if(str[i].compareTo(str[i+1])>= 0){
return false;
}
}
return true;
}
public static boolean iscd(String[] str){
for(int i=0;i < str.length-1 ;i++){
if(str[i].length() >= str[i+1].length() ){
return false;
}
}
return true;
}
}
题目二
1.题目
题目链接:求最小公倍数
2.思路
最小公倍数=两个数相乘/最大公因数。因此本题先求出两数的最大公因数,然后按照公式计算就可以求出了。
3.代码实现
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int a = in.nextInt();
int b = in.nextInt();
if(a < b){
int tmp =a;
a = b;
b = tmp;
}
//最小公倍数=a*b/最大公因数
int ret =a*b/gcb( a, b);
System.out.println(ret);
}
//求最大公因数
public static int gcb(int a,int b){
while(b != 0){
int t = a % b;
a = b;
b = t;
}
return a;
}
}