博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
leetcode-202 Happy Number
阅读量:4120 次
发布时间:2019-05-25

本文共 1540 字,大约阅读时间需要 5 分钟。

关键是当一个数不是happy number是,怎样退出循环

自己的挫方法:使用set保存之前计算的所有数

class Solution {public:    bool isHappy(int n) {        if(n <= 0) return false;        if(n == 1) return true;        set
prev; prev.insert(n); while(n != 1){ int sum = 0; while(n){ int digit = n % 10; sum += digit * digit; n /= 10; } n = sum; if(prev.count(n)) return false; prev.insert(n); } return true; }};
discuss里面的方法1:
Using fact all numbers in [2, 6] are not happy (and all not happy numbers end on a cycle that hits this interval)

class Solution {public:    bool isHappy(int n) {        if(n <= 0) return false;        while(n > 6){            int next = 0;            while(n){                int tmp = n % 10;                next += tmp * tmp;                n /= 10;            }            n = next;        }        return n == 1;    }};
discuss里面的方法2:Use the same way as checking cycles in a linked list

class Solution {public:    bool isHappy(int n) {        if(n <= 0) return false;        int A = nextNum(n); //A指向第一个        int B = nextNum(A); //B指向第二个        while(A != 1 && A != B){            A = nextNum(A); //A每次向前走一步            B = nextNum(B); //B每次向前走两步            B = nextNum(B);        }        return A == 1;    }        int nextNum(int n){        int next = 0;        while(n){            int tmp = n % 10;            next += tmp * tmp;            n /= 10;        }        return next;    }};

转载地址:http://llspi.baihongyu.com/

你可能感兴趣的文章
Java通用字符处理类
查看>>
文件上传时生成“日期+随机数”式文件名前缀的Java代码
查看>>
Java代码检查工具Checkstyle常见输出结果
查看>>
北京十大情人分手圣地
查看>>
Android自动关机代码
查看>>
Android中启动其他Activity并返回结果
查看>>
2009年33所高校被暂停或被限制招生
查看>>
GlassFish 部署及应用入门
查看>>
iWatch报错: Authorization request cancled
查看>>
iWatch报错: Authorizationsession time out
查看>>
如何运行从网上下载的iWatch项目详细步骤.
查看>>
X-code7 beta error: warning: Is a directory
查看>>
Error: An App ID with identifier "*****" is not avaliable. Please enter a different string.
查看>>
X-code beta 开发iWatch项目,运行没有错误,但是某些操作一点就崩,而且找不错误的原因场景一
查看>>
Xcode 报错: Extra argument in call
查看>>
iTunes Connect 上传APP报错: Communication error. please use diagnostic mode to check connectivity.
查看>>
#import <Cocoa/Cocoa.h> 报错 Lexical or Preprocessor Issue 'Cocoa/Cocoa.h' file not found
查看>>
`MQTTClient (~> 0.2.6)` required by `Podfile`
查看>>
X-Code 报错 ld: library not found for -lAFNetworking
查看>>
Bitcode
查看>>