数c++ python个数_LeetCode简单题:202. 快乐数(Python,C++,Java)

一.解法

https://leetcode-cn.com/problems/happy-number/

要点:快慢指针

牵涉到有没有环的时候经常要考虑快慢指针,用来防止无限循环的发生,详见141.环形链表的解法。

Python,C++,Java都用了相同的快慢指针法,如果最后能得到1,那么最终fast和slow最终都为1,如果有环,那么fast和slow都为一个非1的数,事实上所有的非快乐数最终都会进入 4 → 16 → 37 → 58 → 89 → 145 → 42 → 20 → 4 的循环中。

二.Python实现

class Solution:

def isHappy(self, n: int) -> bool:

def get_next(number):

total_sum = 0

while number > 0:

number, digit = divmod(number, 10)

total_sum += digit ** 2

return total_sum

slow_runner = n

fast_runner = get_next(n)

while fast_runner != 1 and slow_runner != fast_runner:

slow_runner = get_next(slow_runner)

fast_runner = get_next(get_next(fast_runner))

return fast_runner == 1

三.C++实现

class Solution {

public:

bool isHappy(int n) {

int fast;

int slow;

fast=n;

slow=n;

do{

slow = getnextnum(slow);

fast = getnextnum(fast);

fast = getnextnum(fast);

}while(slow != fast);

return slow == 1;

}

int getnextnum(int n){

int answer=0;

while(n>0){

int temp=n%10;

answer+=pow(temp,2);

n=n/10;

}

return answer;

}

};

四.java实现

class Solution {

public boolean isHappy(int n) {

int fast;

int slow;

fast=n;

slow=n;

do{

slow = getnextnum(slow);

fast = getnextnum(fast);

fast = getnextnum(fast);

}while(slow != fast);

return slow == 1;

}

public int getnextnum(int n){

int answer=0;

while(n>0){

int temp=n%10;

answer+=Math.pow(temp,2);

n=n/10;

}

return answer;

}

}

你可能感兴趣的:(数c++,python个数)