給定一個(gè)非負(fù)整數(shù) n ,請計(jì)算 0 到 n 之間的每個(gè)數(shù)字的二進(jìn)制表示中 1 的個(gè)數(shù),并輸出一個(gè)數(shù)組。
示例:
- 輸入: n = 2
輸出: [0,1,1]
解釋:
0 -->0
1 -->1
2 -->10
思路:先將每個(gè)數(shù)字轉(zhuǎn)變?yōu)槎M(jìn)制,然后定義一個(gè)函數(shù)count1計(jì)算string中1的個(gè)數(shù).
class Solution {public int[] countBits(int n) {int[] out = new int[n+1];
for(int i=0; iString num = Integer.toBinaryString(i);
out[i] = count1(num);
// System.out.println(out[i]);
}
return out;
}
public int count1(String x){System.out.println(x);
int out=0;
for(int i=0; ichar mid = x.charAt(i);
System.out.println(mid);
if (mid == '1'){out ++;
}
}
return out;
}
}
十進(jìn)制轉(zhuǎn)二進(jìn)制 (n為十進(jìn)制數(shù))
String s=Integer.toBinaryString(n);
十進(jìn)制轉(zhuǎn)八進(jìn)制(n為十進(jìn)制數(shù))
String s=Integer.toOctalString(n);
十進(jìn)制轉(zhuǎn)十六進(jìn)制(n為十進(jìn)制數(shù))
String s=Integer.toHexString(n);
十進(jìn)制轉(zhuǎn)任何進(jìn)制(n為十進(jìn)制數(shù))
String s=Integer.toString(int n,int r);//轉(zhuǎn)化為 r 進(jìn)制,r 的范圍[2,36]
任何進(jìn)制轉(zhuǎn)十進(jìn)制
int n=Integer.parseInt(String s,int r);//將 r 進(jìn)制的字符串 s 轉(zhuǎn)化為十進(jìn)制
2.string類用法
s.length() 返回長度
s.charAt(i) 返回第i處的char,注意別和python中s[i]搞混
你是否還在尋找穩(wěn)定的海外服務(wù)器提供商?創(chuàng)新互聯(lián)www.cdcxhl.cn海外機(jī)房具備T級流量清洗系統(tǒng)配攻擊溯源,準(zhǔn)確流量調(diào)度確保服務(wù)器高可用性,企業(yè)級服務(wù)器適合批量采購,新人活動(dòng)首月15元起,快前往官網(wǎng)查看詳情吧