开发者社区> 问答> 正文

提高字符串到二进制数转换的性能

Ques)有一个二进制格式的输入字符串,11100并且需要计算步骤数,其中步骤号为零。如果数字是odd -> subtract it by 1,if even -> divide it by 2。

例如

28-> 28/2

14-> 14/2

7-> 7-1

6-> 6/2

3-> 3-1

2-> 2/2

1-> 1-1

0->停止

步骤数= 7

我想出了以下解决方案

public int solution(String S) { // write your code in Java SE 8 String parsableString = cleanString(S); int integer = Integer.parseInt(S, 2); return stepCounter(integer); }

private static String cleanString(String S){ int i = 0; while (i < S.length() && S.charAt(i) == '0') i++; StringBuffer sb = new StringBuffer(S); sb.replace(0,i,""); return sb.toString(); }

private static int stepCounter(int integer) { int counter = 0; while (integer > 0) { if (integer == 0) break; else { counter++; if (integer % 2 == 0) integer = integer / 2; else integer--; } } return counter; } 这个问题的解决方案看起来非常简单明了,但是此代码的性能评估让我一无所获。我最初的印象是将字符串转换为int是一个瓶颈,但未能为此找到更好的解决方案。有人可以向我指出此代码的瓶颈吗,可以在哪些方面进行显着改进?

展开
收起
小六码奴 2019-10-03 19:33:19 1007 0
1 条回答
写回答
取消 提交回答
  • 需要减去的次数是1的位数Integer.bitCount()。您需要除以的次数是最高有效位的位置,即Integer.SIZE(32,整数的总位数)Integer.numberOfLeadingZeros()减去一(无需除法1)。我假设对于零输入,结果应为零。所以我们有

    int numberOfOperations = integer == 0 ? 0 : Integer.bitCount(integer) + Integer.SIZE - Integer.numberOfLeadingZeros(integer) - 1;

    2019-10-09 16:26:16
    赞同 展开评论 打赏
问答地址:
问答排行榜
最热
最新

相关电子书

更多
低代码开发师(初级)实战教程 立即下载
冬季实战营第三期:MySQL数据库进阶实战 立即下载
阿里巴巴DevOps 最佳实践手册 立即下载