File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ /*
2+ // 첫번째 풀이,
3+ // int -> string -> bit -> length
4+ // 형변환을 하지 않고 하는 방법 필요
5+ class Solution {
6+ public int hammingWeight(int n) {
7+ String intConvertBit = String.format("%32s", Integer.toBinaryString(n)).replaceAll(" ", "0");
8+
9+ return intConvertBit.replaceAll("0", "").length();
10+ }
11+ }
12+
13+ // 32비트로 굳이 변환할 필요가 없는데..?
14+ // 음수는 안들어오니, 비트 변환 후 바로 체크하여 반환
15+ class Solution {
16+ public int hammingWeight(int n) {
17+ return Integer.toBinaryString(n).replaceAll("0", "").length();
18+ }
19+ }
20+
21+ // 두번째 풀이,
22+ // length말고 counting으로?
23+ class Solution {
24+ public int hammingWeight(int n) {
25+ String s = Integer.toBinaryString(n);
26+
27+ int count = 0;
28+ for (char c: s.toCharArray()) {
29+ if (c == '1') count++;
30+ }
31+
32+ return count;
33+ }
34+ }
35+
36+ // 세번째 풀이
37+ // int형 그대로 사용(달레님 강의 참고하여 풀이)
38+ // 10진수를 0이 될 때까지 계속 2로 나누고 나머지를 모두 연결한다.
39+ class Solution {
40+ public int hammingWeight(int n) {
41+ int cnt = 0;
42+ while (n > 0) {
43+ cnt += n % 2;
44+ n = n /2;
45+ }
46+ return cnt;
47+ }
48+ }
49+ */
50+
51+ // 네번째 풀이
52+ // 비트 조작을 통한 풀이
53+ // 마지막 비트가 1인지 확인
54+ // 비트를 오른쪽으로 한 칸 이동시키고, 왼쪽 빈자리를 0으로 채움
55+ class Solution {
56+ public int hammingWeight (int n ) {
57+ int cnt = 0 ;
58+ while (n > 0 ) {
59+ cnt += (n & 1 );
60+ n >>>= 1 ;
61+ }
62+ return cnt ;
63+ }
64+ }
Original file line number Diff line number Diff line change 1+ class Solution {
2+ public boolean isPalindrome (String s ) {
3+ s = s .replaceAll ("[^a-zA-Z0-9]" , "" ).trim ().toLowerCase ();
4+ if (s .equals ("" )) return true ;
5+
6+ String [] strArr = s .split ("" );
7+ for (int i = 0 ; i < strArr .length /2 ; i ++) {
8+ if (!strArr [i ].equals (strArr [strArr .length -1 -i ])) return false ;
9+ }
10+ return true ;
11+ }
12+ }
You can’t perform that action at this time.
0 commit comments