기본틀 :
using System;
public class Solution {
public int[] solution(string s) {
int[] answer = new int[] {};
return answer;
}
}
풀이 1)
아무 생각 없이 2중 반복문을 통해 s[index]가 0인 개수와 횟수를 카운트
using System;
public class Solution {
public int[] solution(string s) {
int count = 0;
int zeroCount = 0;
while(s.Length != 1)
{
string temp = "";
for(int i = 0; i < s.Length; i++)
{
if(s[i] == '0') zeroCount++;
else temp += s[i];
}
count++;
s = Convert.ToString(temp.Length, 2);
}
return new int[] { count , zeroCount };
}
}
풀이 2)
s.Where()로 요소 중 '1'의 개수를 카운트 한다.
그러면 나머지는 모두 '0'인 요소들이 된다.
using System;
using System.Linq;
public class Solution {
public int[] solution(string s) {
int count = 0;
int zeroCount = 0;
while(s.Length != 1)
{
int oneCount = s.Where(element=> element == '1').Count();
zeroCount += s.Length - oneCount;
s = Convert.ToString(oneCount, 2);
count++;
}
return new int[] { count , zeroCount };
}
}
Convert.ToString()
10진수 -> * 진수로 변환
두 문제에서 10진수를 2진수로 변환하는 방법이 필요했다.
Convert.ToString()을 사용하면 가능했다.
int number = 26;
// 2진수
string binary = Convert.ToString(number, 2); // "11010"
// 8진수
string octal = Convert.ToString(number, 8); // "32"
// 16진수
string hex = Convert.ToString(number, 16); // "1a"
// 3진수
string ternary = Convert.ToString(number, 3); // "222"
추가적으로,
Convert.ToInt32()
원하는 진수 -> 10 진수로 변환
Convert.ToInt32()를 사용하면 원하는 진수를 10진수로 만들어 낼 수 있었다.
// 2진수 -> 10진수
int decimalValue = Convert.ToInt32("1010", 2); // 10
// 16진수 -> 10진수
int hexToDecimal = Convert.ToInt32("1A", 16); // 26
// 8진수 -> 10진수
int octalToDecimal = Convert.ToInt32("17", 8); // 15
// 3진수 -> 10진수
int ternaryToDecimal = Convert.ToInt32("102", 3); // 11
단, ToString()과 ToInt32는 2 ~ 32의 진수 범위 내에서만 사용 가능했다.
'문제 풀기 > C#' 카테고리의 다른 글
79. 카펫 (0) | 2025.02.26 |
---|---|
78. 피보나치 (0) | 2025.02.25 |
76. JadenCase 문자열 만들기 (0) | 2025.02.25 |
75. 최댓값과 최솟값 (0) | 2025.02.24 |
74. 신고 결과 받기 (Distinct, Dictionary Value를 List로 만들기) (0) | 2025.02.24 |