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 = 0; for (int i = 0; i < len; i++) { int n = Convert.ToInt32(s[i].ToString()); int mi = len - i - 1; sum += n * Convert.ToInt32(Math.Pow(2, mi)); } return sum; } /// <summary> /// 将十进制数字转换为二进制字符串 /// </summary> /// <param name="n"></param> /// <returns></returns> private string IntToBin(int n) { StringBuilder sb = new StringBuilder(); do { var s = (n % 2).ToString(); sb.Append(s); n = n / 2; } while (n != 0); 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 = 0; i <= 11; i++) { //将数字依据1的个数存入不同的组 var s = IntToBin(i); var countOne = 0; foreach (var c in s) { if (c == '1') { countOne++; } } if (!HourDic.ContainsKey(countOne)) { HourDic.Add(countOne, new List<int>() { i }); } else { HourDic[countOne].Add(i); } } //将从0到59的数字依次放入MinDic中 for (int i = 0; i <= 59; i++) { var s = IntToBin(i); var countOne = 0; foreach (var c in s) { if (c == '1') { 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 = 0; 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 < 10) { sb.Append("0"); } sb.Append(l2.ToString()); list.Add(sb.ToString()); sb.Clear(); } } } } foreach (var l in list) { Console.WriteLine(l); } return list; } }
转载于:https://www.cnblogs.com/asenyang/p/6732484.html