- 用递归的方法实现字符串逆置
public class Reverse {
public static void main(String[] args) {
String s = "123456";
System.out.println(reverseString(s));
}
public static String reverseString(String s) {
if(s==null) return null;
else if(s.length()==1) return s;
String sub = s.substring(1);
return reverseString(sub)+s.charAt(0);
}
}
- 返回字符串中空格的数量
public class Number {
public static void main(String[] args) {
String s = "aaa b ccc ";
System.out.println(getNumber(s));
}
public static int getNumber(String s) {
char[] c = s.toCharArray();
int count = 0;
for(int i=0;i<c.length;i++) {
if(c[i]==' ') {
count++;
}
}
return count;
}
}
- 罗马数字和阿拉伯数字转换
import java.util.Scanner;
public class RomeToArabic {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println(rToa(sc.nextLine()));
System.out.println(aTor(sc.nextInt()));
}
public static int rToa(String s) {
int[] graph = new int[400];
graph['I'] = 1;
graph['V'] = 5;
graph['X'] = 10;
graph['L'] = 50;
graph['C'] = 100;
graph['D'] = 500;
graph['M'] = 1000;
char[] c = s.toCharArray();
int sum = graph[c[0]];
for (int i = 0; i < c.length - 1; i++) {
if (graph[c[i]] >= graph[c[i + 1]]) {
sum += graph[c[i + 1]];
} else {
sum = sum + graph[c[i + 1]] - 2 * graph[c[i]];
}
}
return sum;
}
public static String aTor(int num) {
String rNum = "";
int[] aArr = { 1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1 };
String[] rArr = {"M","CM","D","CD","C","XC","L","XL","X","IX","V","IV","I"};
if(num<1||num>3999) {
rNum = "-1";
}else {
for(int i=0;i<aArr.length;i++) {
while(num>=aArr[i]) {
rNum += rArr[i];
num -= aArr[i];
}
}
}
return rNum;
}
}