我知道StringBuffer的append()操作花费O(1)时间,与String连接相比,它避免了创建String对象的多个副本的开销.
insert(int offset,char c)怎么样?
我需要重复调用此操作,以便以相反的顺序逐个向StringBuffer对象添加新字符.例如,
StringBuffer sb = new StringBuffer();
sb.insert(0, 'c');
sb.insert(0, 'b');
sb.insert(0, 'a');
System.out.println(sb.toString()); //prints out "abc";
Run Code Online (Sandbox Code Playgroud)
在理想情况下,如果StringBuffer对象内部看起来像链接的字符列表,则每个插入(0,c)应该是O(1).我想确认是否真的如此.
在采访中有人问我以下问题:
每个数字都可以通过2的幂的加法和减法来描述
29 = 2^0 + 2^2 + 2^3 + 2^4。给定一个int n,返回2 ^ i的最小加法和减法得到n。
Example 1:
Input: 15
Output: 2
Explanation: 2^4 - 2^0 = 16 - 1 = 15
Example 2:
Input: 8
Output: 1
Example 3:
Input: 0
Output: 0
Run Code Online (Sandbox Code Playgroud)
下面是我得到的,但是有什么方法可以改善此问题,或者有什么更好的方法可以解决上述问题?
public static int minPowerTwo(int n) {
if (n == 0) {
return 0;
}
if (Integer.bitCount(n) == 1) {
return 1;
}
String binary = Integer.toBinaryString(n);
StringBuilder sb = new StringBuilder();
sb.append(binary.charAt(0));
for (int i = …Run Code Online (Sandbox Code Playgroud)