public class Solution
{
/// <summary>
/// 将二进制字符串转为十进制数字
/// </summary>
/// <param name="s"></param>
/// <returns></returns>
private int BinToInt(string s)
{
var len = s.Length;
int[] bins = new int[len]; int sum = ; for (int i = ; i < len; i++)
{
int n = Convert.ToInt32(s[i].ToString());
int mi = len - i - ;
sum += n * Convert.ToInt32(Math.Pow(, mi));
} return sum;
} /// <summary>
/// 将十进制数字转换为二进制字符串
/// </summary>
/// <param name="n"></param>
/// <returns></returns>
private string IntToBin(int n)
{
StringBuilder sb = new StringBuilder();
do
{
var s = (n % ).ToString();
sb.Append(s);
n = n / ;
} while (n != ); var list = sb.ToString().Reverse();
sb.Clear();
foreach (var c in list)
{
sb.Append(c);
}
return sb.ToString();
} //key表示1的个数,value是对应的可能的数值
Dictionary<int, List<int>> HourDic = new Dictionary<int, List<int>>();
Dictionary<int, List<int>> MinDic = new Dictionary<int, List<int>>(); public IList<string> ReadBinaryWatch(int num)
{
//将从0到11的数字依次放入HourDic中
for (int i = ; i <= ; i++)
{
//将数字依据1的个数存入不同的组
var s = IntToBin(i);
var countOne = ;
foreach (var c in s)
{
if (c == '')
{
countOne++;
}
}
if (!HourDic.ContainsKey(countOne))
{
HourDic.Add(countOne, new List<int>() { i });
}
else
{
HourDic[countOne].Add(i);
}
} //将从0到59的数字依次放入MinDic中
for (int i = ; i <= ; i++)
{
var s = IntToBin(i);
var countOne = ;
foreach (var c in s)
{
if (c == '')
{
countOne++;
}
}
if (!MinDic.ContainsKey(countOne))
{
MinDic.Add(countOne, new List<int>() { i });
}
else
{
MinDic[countOne].Add(i);
}
} IList<string> list = new List<string>(); for (int i = ; i <= num; i++)
{
//i用于小时,
//j用于时间,
int j = num - i;
StringBuilder sb = new StringBuilder();
if (HourDic.ContainsKey(i) && MinDic.ContainsKey(j))
{
//列出可能的小时
var list1 = HourDic[i];//用于存储所有可能的小时 //列出可能的分钟
var list2 = MinDic[j];//用于存储所有可能的分钟 //做笛卡尔乘积,存入list
foreach (var l1 in list1)
{
foreach (var l2 in list2)
{
sb.Append(l1.ToString());
sb.Append(":");
if (l2 < )
{
sb.Append("");
}
sb.Append(l2.ToString());
list.Add(sb.ToString());
sb.Clear();
}
}
}
} foreach (var l in list)
{
Console.WriteLine(l);
} return list;
}
}

https://leetcode.com/problems/binary-watch/#/description

05-11 16:02