How to optimize the following code in java where I've to get bitwise OR of two very long binary strings?

huangapple 未分类评论47阅读模式
标题翻译

How to optimize the following code in java where I've to get bitwise OR of two very long binary strings?

问题

我已经写了以下代码来获取两个字符串的**按位或(bitwise or)**操作结果。但是,当我传递较长的字符串时,执行时间太长。我该如何进行优化

static String or_str(String s1, String s2){
    StringBuilder result = new StringBuilder();
    int length = Math.min(s1.length(), s2.length()); // 取两个字符串长度的较小值
    
    for(int i = 0; i < length; i++){
        if(s1.charAt(i) == '1' || s2.charAt(i) == '1') {
            result.append("1");
        } else {
            result.append("0"); // 如果两个字符都不是 '1',则按位或结果为 '0'
        }
    }
    
    return result.toString();
}
英文翻译

I've written the following code to get the bitwise or of two strings. But, it's taking way too long when I pass long strings. How can I optimize it?

 static String or_str(String s1, String s2){
            String result=&quot;&quot;;
            for(int i=0; i&lt;s1.length(); i++){
                if(s1.charAt(i)==&#39;1&#39;||s2.charAt(i)==&#39;1&#39;)
                result+=&quot;1&quot;;
            }
            return result;
        }

答案1

得分: 2

如果您只需要计算1的数量就像评论中提到的那样您可以使用以下示例代码

static int countBitwiseOr(String s1, String s2) {
    int result = 0;
    for (int i = 0; i < s1.length(); i++) {
        if (s1.charAt(i) == '1' || s2.charAt(i) == '1')
            result += 1;
    }
    return result;
}

以避免大量的计算开销

**在评论中提出的建议的符合API的编辑解决方案**

如果您需要符合API的结果返回包含所有正结果的字符串),您仍然可以

> 使用Java 11

static String or_str(String s1, String s2){
    return "1".repeat(countBitwiseOr(s1, s2));
}

> 使用Java 11

static String or_str(String s1, String s2){
    return Stream.generate(() -> "1").limit(countBitwiseOr(s1, s2)).collect(joining());
}
英文翻译

If you need just the amount of ones, like can be found on comments, you can use sample like this:

static int countBitwiseOr(String s1, String s2) {
	int result = 0;
	for (int i = 0; i &lt; s1.length(); i++) {
		if (s1.charAt(i) == &#39;1&#39; || s2.charAt(i) == &#39;1&#39;)
			result += 1;
	}
	return result;
}

to avoid lot of calculation overhead.

Edit suggested API conform solution proposed in comments

If you need to rest API conform (return a string containing all the positive results) you then still can:

> with Java 11

 static String or_str(String s1, String s2){
    return &quot;1&quot;.repeat(countBitwiseOr(s1,s2));
 }

> with Java 11

 static String or_str(String s1, String s2){
   return Stream.generate(() -&gt; &quot;1&quot;).limit(countBitwiseOr(s1,s2)).collect(joining());
 }

答案2

得分: 0

如果您想要一个真正的位“或”操作,您还需要在条件不匹配的情况下输出零。如果您想提高性能,您可以知道输出的长度,因此在每次迭代时,可以从开始就使用一个预定义长度的字符数组。

以下是一个简单的字符串位或实现,它返回一个字符串:

public static void main(String[] args) {
    String s1 = "1011010100100101110";
    String s2 = "011011101101001000100110001";
    System.out.println(or_str(s1, s2));
}

static String or_str(String s1, String s2){
    char[] res = new char[s1.length()];
    for(int i=0; i<s1.length(); i++){
        if(s1.charAt(i)=='1'||s2.charAt(i)=='1')
            res[i] ='1';
        else
            res[i] ='0';
    }
    return new String(res);
}

如果您运行这个代码,输出将会是:

1111111111110111111
英文翻译

If you want a real bitwise "OR" you need also to output a zero in case your condition does not match. If you want to improve performance you know the length of the output so instead of creating a new string on each iteration you can use a character array with a pre-defined length from the start.

Here is a simple implementation of a bitwise or for strings which returns a string:

public static void main(String[] args) {
    String s1 = &quot;1011010100100101110&quot;;
    String s2 = &quot;011011101101001000100110001&quot;;
    System.out.println(or_str(s1, s2));
}

static String or_str(String s1, String s2){
    char[] res = new char[s1.length()];
    for(int i=0; i&lt;s1.length(); i++){
        if(s1.charAt(i)==&#39;1&#39;||s2.charAt(i)==&#39;1&#39;)
            res[i] =&#39;1&#39;;
        else
            res[i] =&#39;0&#39;;
    }
    return new String(res);
}

If you run this, the output will be:

1111111111110111111

huangapple
  • 本文由 发表于 2020年3月16日 20:06:33
  • 转载请务必保留本文链接:https://java.coder-hub.com/60705695.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定