using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Collections; //输出结果为:1366 //2^15 = 32768 and the sum of its digits is 3 + 2 + 7 + 6 + 8 = 26. //What is the sum of the digits of the number 2^1000? //解题思路,利用键值对,键存储位权,值存储值 namespace Problem16 { class Program { static void Main(string[] args) { Hashtable ht = GetHashtable(1000); PrintHashtable(ht); Console.WriteLine("2^1000的所有各项相加之和为:{0}",AddAll(ht)); } //方法用于返回一个变型存储的整数用hashtable存储,key表示位权 //value表示该位权的值,例如ht.add(1,2)意思是个位数字为2,ht.add(2,5) //意思是十位为5以此类推。 #region GetHashtable() public static Hashtable GetHashtable(int mutiplenum) { Hashtable ht = new Hashtable(); int tmp = 0, low = 0, high = 0; ht.Add(1,2); for (int i = 1; i < mutiplenum; i++) { for (int j = 1; j <= ht.Count; j++) { if ((int)ht[j] * 2 < 10) { tmp = (int)ht[j]; low = tmp * 2+high; high = 0; ht.Remove(j); ht.Add(j, low); } else { tmp = (int)ht[j]; low = tmp * 2 % 10+high; high = 1; ht.Remove(j); ht.Add(j,low); } } //如果不等于0,则加入到最后面去 if (high != 0) { ht.Add(ht.Count+1,high); high = 0; } } return ht; } #endregion //输出hashtable中的值来查看整个数 #region PrintHashtable public static void PrintHashtable(Hashtable ht) { for (int i = ht.Count; i>=1 ; i--) { Console.Write("{0}", (int)ht[i]); } Console.WriteLine(); } #endregion //把hashtabale里面的值加起来 #region 加和所有项 public static int AddAll(Hashtable ht) { int sum = 0; foreach (DictionaryEntry de in ht) { sum += (int)de.Value; } return sum; } #endregion } }