题目
In a factory a printer prints labels for boxes. For one kind of boxes the printer has to use colors which, for the sake of simplicity, are named with letters from a to m
.
The colors used by the printer are recorded in a control string. For example a “good” control string would be aaabbbbhaijjjm
meaning that the printer used three times color a, four times color b, one time color h then one time color a…
Sometimes there are problems: lack of colors, technical malfunction and a “bad” control string is produced e.g. aaaxbbbbyyhwawiwjjjwwm with letters not from a to m.
You have to write a function printer_error
which given a string will output the error rate of the printer as a string representing a rational whose numerator is the number of errors and the denominator the length of the control string. Don’t reduce this fraction to a simpler expression.
The string has a length greater or equal to one and contains only letters from ato z.
Examples:
s="aaabbbbhaijjjm"
error_printer(s) => "0/14"
s="aaaxbbbbyyhwawiwjjjwwm"
error_printer(s) => "8/22"
代码
using System;
public class Printer
{
public static string PrinterError(String s)
{
int count=0;
for(int i=0;i<s.Length;i++){
char c=s[i];
if(c>'m') count++;
}
return string.Format("{0}/{1}",count,s.length);
}
}
解题思路
本题涉及到字母顺序与数字的关系,以及字符串输出的格式。
1. String.Format Method
https://docs.microsoft.com/zh-cn/dotnet/api/system.string.format?redirectedfrom=MSDN&view=netframework-4.7.2
2. 由题意可知m之后的字母都算是错误的,因此,让字符串中的字符c大于’m’即可找出所有排在m之后的字母。