51Nod--1015 水仙花数

51Nod:  http://www.51nod.com/onlineJudge/questionCode.html#!problemId=1015
 
基准时间限制:1 秒 空间限制:131072 KB 分值: 5 难度:1级算法题
 
水仙花数是指一个 n 位数 ( n >= 3 ),它的每个位上的数字的 n 次幂之和等于它本身。(例如:1^3 + 5^3 + 3^3 = 153)
给出一个整数M,求 >= M的最小的水仙花数。
 
Input
一个整数M(10 <= M <= 1000)
Output
输出>= M的最小的水仙花数
Input示例
99
Output示例
153

 

题解: 

简单水题, 打表法给出水仙花数, 然后在水仙花数组中二分查找得到answer。 

 

 

#include <iostream> 
#include <cstdio> 
#include <cstdlib>
#include <cstring> 
using namespace std; 
const int maxn = 10000; 

int cnt, vt[maxn]; 

int Mypow(int num, int times){
	int ans = 1; 
	while(times){
		ans *= num; 
		times--; 
	} 
	return ans; 
}

void init(){
	int i; 
	cnt = 0; vt[cnt++] = 0; 
	for(i=100; i<=999; ++i){
		if(i == ( Mypow(i%10, 3) + Mypow((i/10)%10, 3) + Mypow((i/100)%10, 3) )){
			vt[cnt++] = i; 
		}
	}
	for(i=1000; i<=9999; ++i){
		if(i == (Mypow(i%10, 4) + Mypow( (i/10)%10, 4) + Mypow( (i/100)%10, 4) + Mypow((i/1000)%10, 4)) ){
			vt[cnt++] = i; 
		}
	}
}

int Find(int n){
	int mid, l = 0, r = cnt-1; 
	while(l <= r){
		mid = l + (r-l)/2; 
		if(vt[mid] >= n && vt[mid-1]<n){
			return vt[mid]; 
		}else if(vt[mid-1] >= n){
			r = mid - 1; 
		}else{
			l = mid + 1; 
		}
	}
	return -1; 
}

int main(){
	//freopen("in.txt", "r", stdin); 

	int n, ans; 
	init(); 
	while(scanf("%d", &n) != EOF){
		ans = Find(n); 
		printf("%d\n",  ans);
	}
	return 0; 
}

 

posted @ 2016-10-26 10:40  zhang--yd  阅读(231)  评论(0编辑  收藏  举报