官术网_书友最值得收藏!

  • The Modern C# Challenge
  • Rod Stephens
  • 187字
  • 2021-08-13 15:23:58

19. Armstrong numbers

The obvious approach to this problem is to loop through the candidate numbers, convert each into a string, pull apart its digits, raise the digits to the correct power, and see if they add up to the original number.

The following method loops through values up to the desired maximum to build a list of Armstrong numbers:

// Look for Armstrong numbers <= max.
private List<long> FindArmstrongNumbers(long max)
{
List<long> values = new List<long>();
for (long i = 1; i <= max; i++)
if (IsArmstrong(i)) values.Add(i);
return values;
}

This method calls the following IsArmstrong method to see if a value is an Armstrong number:

// Return true if this is an Armstrong number.
private bool IsArmstrong(long number)
{
// Get the number's digits.
long copy = number;
List<long> digits = new List<long>();
while (copy > 0L)
{
digits.Add(copy % 10L);
copy = copy / 10L;
}

// Add the digits' powers.
long total = 0;
long numDigits = digits.Count;
foreach (long digit in digits)
total += (long)Math.Pow(digit, numDigits);
return (total == number);
}

The only non-obvious pieces in this method are the two statements that calculate the digit and update the copy of the number. The calculation copy % 10L returns the number's least significant digit. For example, 417 % 10L returns 7.

The calculation copy / 10L returns the number with its least significant digit removed. For example, 417 % 10L returns 41.

Download the ArmstrongNumbers example solution to see additional details.

主站蜘蛛池模板: 南京市| 三都| 抚宁县| 兴城市| 二连浩特市| 桐乡市| 房山区| 马边| 抚州市| 铁力市| 年辖:市辖区| 资兴市| 普兰店市| 泗阳县| 永嘉县| 三台县| 山丹县| 延川县| 蓬莱市| 奉贤区| 隆尧县| 穆棱市| 阳城县| 郎溪县| 涞源县| 乌苏市| 韩城市| 丹江口市| 青阳县| 古浪县| 鱼台县| 闸北区| 同仁县| 开远市| 宁阳县| 略阳县| 河北省| 维西| 威信县| 南澳县| 宣汉县|