每日一题
1017.负二进制转换
class Solution {
public String baseNeg2(int n) {
if(n==0){
return "0";
}
int[] bits=new int[32];
for(int i=0;i32&&n!=0;i++){
if((n&1)!=0){
bits[i]++;
if((i&1)!=0){
bits[i+1]++;
}
}
n>>=1;
}
int carry=0;
for(int i=0;i32;i++){
int val=carry+bits[i];
bits[i]=val&1;
carry=(val-bits[i])/(-2);
}
int pos=31;
StringBuilder res=new StringBuilder();
while(pos>=0&&bits[pos]==0){
pos--;
}
while(pos>=0){
res.append(bits[pos]);
pos--;
}
return res.toString();
}
}
class Solution {
public String baseNeg2(int n) {
if(n==0){return "0";}
String ans="";
for(int i=0;n>0;i++){
ans=(n&1)+ans;
if((i&1)==1){n+=(n&1)1;}
n>>=1;
}
return ans;
}
}
效率不高
344.翻转字符串
class Solution {
public void reverseString(char[] s) {
int n=s.length;
for(int left=0,right=n-1;leftright;++left,--right){
char tmp=s[left];
s[left]=s[right];
s[right]=tmp;
}
}
}
557. 反转字符串中的单词 III
class Solution {
public String reverseWords(String s) {
StringBuffer ret = new StringBuffer();
int length = s.length();
int i = 0;
while (i length) {
int start = i;
while (i length && s.charAt(i) != ' ') {
i++;
}
for (int p = start; p i; p++) {
ret.append(s.charAt(start + i - 1 - p));
}
while (i length && s.charAt(i) == ' ') {
i++;
ret.append(' ');
}
}
return ret.toString();
}
}
服务器托管,北京服务器托管,服务器租用 http://www.fwqtg.net