3、计算字符串中含有的不同字符的个数
编写一个函数,计算字符串中含有的不同字符的个数。字符在 ASCII码范围内(0~127,包括 0 和127),换行表示结束符,不算在字符里。不在范围内的不作统计。多个相同的字符只计算一次例如,对于字符串 abaca 而言,有 a、b、c 三种不同的字符,因此输出 3。数据范围:1 <=n<=500
输入描述
输入一行没有空格的字符串。
输出描述
输入字符串中范围在(0-127,包括0和127)字符的种数。
例如
输入:
abc
输出:
3
输入:
аaa
输出:
1
思路
首先将字符串转换为字符数组,然后遍历0~127,同时遍历字符数组,将数字和字符比较,一旦相等则字符种数加1,同时跳出本层字符数组遍历,最后输出字符种数。
具体实现
java实现
public static int CharNumber(String str) {
int count = 0;
char[] ch = str.toCharArray();
for (int i = 0; i <= 127; i++) {
for (int j = 0; j < ch.length; j++) {
if (i == ch[j]) {
count++;
break;
}
}
}
return count;
}
public static void main(String[] args) {
System.out.println("输入:");
Scanner scan = new Scanner(System.in);
String str = scan.next();
int count = CharNumber(str);
System.out.println("输出:");
System.out.println(count);
}
4、从键盘输入两个数字n,m,求解m和n的最小公倍数。
思路
将n和m中较小的数赋予中间变量x,x是递增的,当x整除n且x整除m时输出x。
具体实现
java实现
public static int LCM(int n,int m){
int x=0;
x=(n<m)?n:m;
while (x%n!=0||x%m!=0){
x++;
}
return x;
}
public static void main(String[] args) {
System.out.println("输入两个数字:");
Scanner scan=new Scanner(System.in);
int n=scan.nextInt();
int m=scan.nextInt();
int lcm=LCM(n,m);
System.out.println("最小公倍数为:");
System.out.println(lcm);
}