日期:2014-05-20 浏览次数:20840 次
public static void main(String[] args) { Scanner in = new Scanner(System.in); System.out.println("Enter a word:"); String a = in.next(); System.out.println("Enter another string:"); String b = in.next(); if (a.length()!= b.length()){ System.out.println(b + "is not permutation of the character of " + a); }else{ //如果可以用到工具类就不用自己写排序方法了 //用Arrays.sort(a.toCharArray())也可以完成 if(sort(a).equals(sort(b))){ System.out.println("equality"); }else{ System.out.println("inequality"); } } } public static String sort(String str) { char[] charArray = str.toCharArray(); //这里我就使用了选择排序,当然你也可以用冒泡排序,插入排序 int flag; char temp; for(int i=0;i<charArray.length;i++) { flag = i; for(int j=i+1;j<charArray.length;j++) { if(charArray[flag] > charArray[j]) { flag = j; } } if(flag != i) { temp = charArray[i]; charArray[i] = charArray[flag]; charArray[flag] = temp; } } return String.valueOf(charArray); }
------解决方案--------------------
第二题很简单的哦~~
public class StringComparison { public static void main(String[] args) { String stra = "CCAV没有泷泽萝拉"; String strb = "泷V萝没泽有AC拉C"; String str1 = stra.toUpperCase(); String str2 = strb.toUpperCase(); int count1 = 0, count2 = 0; if (str1.equals(str2)) { System.out.println(strb + " 与 " + stra + " 完全相同"); } else if (str1.length() == str2.length()) { for (int i = 0; i < str1.length(); i++) { for (int j = 0; j < str2.length(); j++) { if (str1.charAt(i) == str2.charAt(j)) { count2++; } } for (int k = 0; k < str1.length(); k++) { if (str1.charAt(i) == str1.charAt(k)) { count1++; } } if (count1 == count2) { count1 = count2 = 0; } else { System.out.println(strb + " 不是 " + stra + " 的顺序打乱");//false System.exit(0); } } System.out.println(strb + " 是 " + stra + " 的顺序打乱");//true } else { System.out.println(strb + " 不是 " + stra + " 的顺序打乱");//false } } }
------解决方案--------------------
第一题,用 Integer.bitCount();
for example
Scanner sc = new Scanner(System.in); int num = sc.nextInt(); System.out.println("1的个数是: " + Integer.bitCount(num));