天天看点

华为机试题: 水仙花数

描述: 

水仙花数又称阿姆斯特朗数。

水仙花数是指一个n 位数( n≥3 ),它的每个位上的数字的n 次幂之和等于它本身。(例如:1^3 + 5^3 + 3^3 = 153)

求输入的数字是否为水仙花数

注意:是每位数的n次幂,并且少于三位的数,也不是水仙花数

#include <stdlib.h>
#include <math.h>
#include "oj.h"

// 功能:判断输入 nValue 是否为水仙花数
// 输入: nValue为正整数
// 输出:无
// 返回:如果输入为水仙花数,返回1,否则返回0
unsigned int IsDaffodilNum(unsigned int  nValue)
{
	int data[10] = { 0 };
	int i = 0,sum = 0;
	unsigned int temp = nValue;
	int bits = 0;

	/*先判断数的位数,注意数小于三位不是水仙花数*/
	while (temp)
	{
		bits++;
		temp = temp / 10;
	}

	if (bits < 3)
	{
		return 0;
	}

	/*求出每一位的数*/
	temp = nValue;
	while (temp)
	{
		data[i++] = temp % 10;
		temp = temp / 10;
	}

	/*判断是否是水仙花数*/
	sum = 0;
	for (i= 0; i < bits; i++)
	{
		sum += pow(static_cast<double>(data[i]), bits);
	}

	if (sum == nValue)
	{
		return 1;
	}
	return 0;
}