日期:2014-05-20 浏览次数:20657 次
public static String and(String str1, String str2) { StringBuffer sb = new StringBuffer(str1.length()); for (int i = 0; i < str1.length(); i++) { if (str1.charAt(i) == str2.charAt(i) && str2.charAt(i) == '1') { sb.append("1"); } else { sb.append("0"); } } return sb.toString(); } public static String or(String str1, String str2) { StringBuffer sb = new StringBuffer(str1.length()); for (int i = 0; i < str1.length(); i++) { if (str1.charAt(i) == '1' || str2.charAt(i) == '1') { sb.append("1"); } else { sb.append("0"); } } return sb.toString(); }
------解决方案--------------------
for example
System.out.println(and("0101", "1110")); System.out.println(or("0101", "1110")); System.out.println(xor("0101", "1110")); System.out.println(not("0101")); public static String and(String s1, String s2) { return new BigInteger(s1, 2).and(new BigInteger(s2, 2)).toString(2); } public static String or(String s1, String s2) { return new BigInteger(s1, 2).or(new BigInteger(s2, 2)).toString(2); } public static String xor(String s1, String s2) { return new BigInteger(s1, 2).xor(new BigInteger(s2, 2)).toString(2); } public static String not(String s) { return new BigInteger(s, 2).not().toString(2); }