指標_快樂數字

 avatar
user_3763047219
c_cpp
2 years ago
917 B
7
Indexable
Never
#include "pch.h"
#include <iostream>
#include <stdio.h>

#include <stdbool.h>
int next_n(int);
bool contains(int*, int, int);
bool isHappy(int);


int next_n(int n) {
	int n2 = n;
	int *sum = &n;
	int size = 1;
	while (n > 0) {
		if (contains(sum, size, *sum) == 1) {
			sum++;
			*sum = 0;
			while (n2 > 0) {
				*sum = *sum + (n2 % 10)*(n2 % 10);
				n2 = n2 / 10;
			}
			n2 = *sum;
			size++;
			if (*sum == 1) {
				return 1;
			}
		}
		else {
			return 0;
		}
	}
}

bool contains(int* history, int size, int n) {
	int i = 1;
	while (i<= size) {
		if (n == *(history - i)) {
			return 0;
		}
		i++;
	}
	return 1;
}

bool isHappy(int n) {
	if (next_n(n) == 1) {
		return 1;
	}
	else {
		return 0;
	}
}

#include <stdio.h>


int main() {
	int n;
	scanf("%d", &n);
	if (isHappy(n)) {
		printf("true");
	}
	else {
		printf("false");
	}
	return 0;
}