zoukankan      html  css  js  c++  java
  • Happy Number

    解决这个问题的思路:
    发现规律的图片
    第一步:从上图中,我们能够发现:在闭区间[1,13]内的全部数经过次数有限的迭代后,它们将会变成1或者4。而1是happy number,4不是happy number。进而能够推断出闭区间[1,13]内的全部数的happy性。

    第二步:以下我做了一个大胆的如果。全部的正数经过可接受的有限次迭代后都将变成1或者4。

    因为在数学上给出证明所需的时间远远大于用程序验证。所以暂且不进行数学证明,直接进行在线编程。结果正确。

    代码例如以下:

    class Solution {
    public:
        bool isHappy(int n) {
            int quotient, remainder;
            vector<int> digitalArr;
    
            quotient = n;
            int i = 1;
            while(true) {
    
                digitalArr.clear();
                for(; quotient != 0; ) {
                    remainder = quotient % 10;
                    quotient = quotient / 10;
                    if(remainder != 0)
                    digitalArr.push_back(remainder);
                }
    
                quotient = 0;
                for(vector<int>::iterator iter = digitalArr.begin(); iter != digitalArr.end(); iter++) {
                        quotient = quotient + (*iter) * (*iter);
                }
    
                if(quotient == 1 || quotient == 4)
                    break;
            }
            if(quotient == 1)
                return true;
            else
                return false;
        }
    };
  • 相关阅读:
    hdu 1106 排序(排序)
    hdu 1040 As Easy As A+B(排序)
    hdu 1029 Ignatius and the Princess IV(排序)
    mysql-9索引
    mysql-8 alter命令
    mysql-7事务管理
    mysql-6正则表达式
    http协议
    9-2交互体验
    9-2专项测试下午
  • 原文地址:https://www.cnblogs.com/llguanli/p/8508244.html
Copyright © 2011-2022 走看看