日期:2014-05-20  浏览次数:20684 次

java求教2个任意相同长度的(01)字符串如何快速的进行'与'或者'或'操作
java求教2个任意相同长度的(01)字符串如何快速的进行'与'或者'或'操作

例如 0101 | 1110 = 1111 (要任意长度字符串 效率第一的)

------解决方案--------------------
Java code

    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
Java code
    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);
    }