문제 풀기/C#
77. 이진 변환 반복하기 (Convert.int32, Convert.ToString)
kagan-draca
2025. 2. 25. 14:44
기본틀 :
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의 진수 범위 내에서만 사용 가능했다.