a부터 b사이에 k라는 숫자가 몇 번 들어 있는지 출력하시오
예) ? 11 15 1
출력) 6
그러니까 "11 15 1"이라고 입력했다면, 11부터 15까지의 숫자 (11, 12, 13, 14, 15) 중 '1’이라는 숫자가 몇번 나오는지를 출력하는 문제인데요,
C#으로는 다음과 같이 짤 수 있습니다.
// a부터 b사이에 k라는 숫자가 몇 번 들어 있는지 출력하시오.
// 예) ? 11 15 1
// 출력) 6
using System;
using System.Linq;
var strNums = Console.ReadLine();
try
{
var nums = strNums.Split(' ')
.Select(x => int.Parse(x))
.Take(3)
.ToArray();
var (first, last, find) = (nums[0], nums[1], nums[2]);
var range = Enumerable.Range(first, last - first + 1);
var count = 0;
foreach (var n in range)
{
var num = n;
while (true)
{
var f = num % 10;
if (f == find)
count++;
num /= 10;
if (num == 0)
break;
}
}
Console.WriteLine(count);
}
catch
{
Console.WriteLine("Invalid Input.");
}
코드보다는 문제에 집중해서 전개한 코드인데요, 이 코드보다 더 깔끔한 C# 코드라면 어떤게 있을까요?
using System;
using System.Linq;
var input = Array.ConvertAll(Console.ReadLine().Split(' '), int.Parse);
var str = string.Empty;
var c = char.Parse(input[2].ToString());
for (var i = input[0]; i <= input[1]; i++)
{
str += i;
}
Console.WriteLine(str.Count(s => s == c));
use std::io::{self, Write};
fn main() {
loop {
// 숫자 입력
let mut input = String::new();
print!("? ");
io::stdout().flush().unwrap();
io::stdin().read_line(&mut input).expect("Invalid input.");
let inputs: Vec<&str> = input.split(' ').collect();
if inputs.len() < 3 {
continue;
}
let first: u32 = match inputs[0].parse() {
Ok(v) => v,
_ => {
continue;
}
};
let last: u32 = match inputs[1].parse() {
Ok(v) => v,
_ => {
continue;
}
};
let num = match inputs[2].chars().next() {
Some(v) => v,
_ => {
continue;
}
};
let mut merge = String::new();
for n in first..last + 1 {
merge.push_str(n.to_string().as_str());
}
let mut count = 0;
for c in merge.chars() {
if c == num {
count += 1;
}
}
println!("{}", count);
}
}