zoukankan      html  css  js  c++  java
  • 浙大保研2019年上机题 7-1 Happy Numbers (20分)

    7-1 Happy Numbers (20分)

    A happy number is defined by the following process: Starting with any positive integer, replace the number by the sum of the squares of its digits in base-ten, and repeat the process until the number either equals 1 (where it will stay), or it loops endlessly in a cycle that does not include 1. Those numbers for which this process ends in 1 are happy numbers and the number of iterations is called the degree of happiness, while those that do not end in 1 are unhappy numbers (or sad numbers). (Quoted from Wikipedia)

    For example, 19 is happy since we obtain 82 after the first iteration, 68 after the second iteration, 100 after the third iteration, and finally 1. Hence the degree of happiness of 19 is 4.

    On the other hand, 29 is sad since we obtain 85, 89, 145, 42, 20, 4, 16, 37, 58, and back to 89, then fall into an endless loop. In this case, 89 is the first loop number for 29.

    Now your job is to tell if any given number is happy or not.

    Input Specification:

    Each input file contains one test case. For each case, the first line gives a positive integer N (≤100). Then N lines follow, each contains a positive integer (no more than 104) to be tested.

    Output Specification:

    For each given number, output in a line its degree of happiness if it is happy, or the first loop number if it is sad.

    Sample Input:

    3
    19
    29
    1
    

    Sample Output:

    4
    89
    0
    

    happy number指的是,一个数字,各位数字的平方进行相加,可以进行迭代,迭代一次,幸福度+1, 如果造成循环,则输出循环的数字,如果不造成循环(最终为1),则输出幸福度。

    #include <iostream>
    #include <cmath>
    #include <unordered_map>
    using namespace std;
    int main() {
        // freopen("in.txt", "r", stdin);
        // freopen("out.txt", "w", stdout);
        int N, tmp;
        scanf("%d", &N);
        while(N--) {
            scanf("%d", &tmp);
            unordered_map<int, bool> m;
            m[tmp] = 1;
            int happy = 0;
            while(tmp != 1) {
                string s = to_string(tmp);
                tmp = 0;
                for(int i = 0; i < s.size(); i++) 
                    tmp += pow((s[i] - '0'), 2);
                if(m[tmp] == 1) break;
                else m[tmp] = 1;
                happy++;
            }
            printf("%d
    ", tmp == 1 ? happy: tmp);
        }
        return 0;
    }
    
  • 相关阅读:
    android NDK开发及调用标准linux动态库.so文件
    android ndk增加对stl的支持
    Android中JNI的使用方法
    OCP-1Z0-052-V8.02-55题
    OCP-1Z0-053-V12.02-162题
    OCP-1Z0-052-V8.02-52题
    OCP-1Z0-052-V8.02-50题
    OCP-1Z0-052-V8.02-49题
    Android 中Java 和C/C++的相互调用方法
    用JNI调用C或C++动态联接库入门
  • 原文地址:https://www.cnblogs.com/littlepage/p/13194679.html
Copyright © 2011-2022 走看看