Sitemap
Jet丁Neat Coding

Jet丁Neat Coding

LeetCode Happy number

--

LeetCode 幸福数字

Contents

Javascript. 1

方案:… 1

测试案例:… 2

Go. 4

方案:… 4

使用案例:… 5

Rust. 6

方案:… 6

测试案例:… 7

Kotlin: 8

方案:… 8

测试案例:… 8

Python3: 9

方案:… 9

测试案例:… 10

Java: 10

方案:… 10

测试案例:… 11

C++: 12

方案:… 12

测试案例:… 13

C#: 14

方案:… 14

测试案例:… 15

Write an algorithm to determine if a number is “happy”.

A happy number is a number defined by the following process: Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not include 1. Those numbers for which this process ends in 1 are happy numbers.

Example:

Input: 19

Output: true

Explanation:

12 + 92 = 82

82 + 22 = 68

62 + 82 = 100

Get Jet丁Neat Coding’s stories in your inbox

Join Medium for free to get updates from this writer.

12 + 02 + 02 = 1

Javascript

方案:

var isHappy = function (n) {
let set = new Set();
while (!set.has(n)) {
set.add(n);
let v = 0;
while (n > 0) {
v += Math.pow(n % 10, 2);
n = Math.floor(n / 10);
}
n = v;
}
return n == 1;
};

测试案例:

describe("isHappy()", function () {
it("test1", function () {
// 1. ARRANGE
let num = 19;

// 2. ACT
var result = isHappy(num);

// 3. ASSERT
expect(result).to.be.equal(true);
});

it("test2", function () {
// 1. ARRANGE
let num = 4;

// 2. ACT
var result = isHappy(num);

// 3. ASSERT
expect(result).to.be.equal(false);
});

it("test3", function () {
// 1. ARRANGE
let num = 123;

// 2. ACT
var result = isHappy(num);

// 3. ASSERT
expect(result).to.be.equal(false);
});
});

Go

方案:

func isHappy(n int) bool {
m := make(map[int]bool)
ok := false
for !ok {
m[n] = true
v := 0
for n > 0 {
v += int(math.Pow(float64(n%10), 2))
n /= 10
}
n = v
_, ok = m[n]
}
return n == 1
}

使用案例:

func Test_isHappy(t *testing.T) {
type args struct {
n int
}
tests := []struct {
name string
args args
want bool
}{
{"test1", args{n: 19}, true},
{"test2", args{n: 4}, false},
{"test3", args{n: 123}, false},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := isHappy(tt.args.n); got != tt.want {
t.Errorf("isHappy() = %v, want %v", got, tt.want)
}
})
}
}

Rust

方案:

impl Solution {
pub fn is_happy(n: i32) -> bool {
let mut hs = std::collections::HashSet::new();
let mut t = n;
while !hs.contains(&t) {
hs.insert(t);
let mut v = 0;
while t > 0 {
v += i32::pow(t % 10, 2);
t /= 10;
println!("{0} {1}", t, v);
}
t = v;
}
return t == 1;
}
}

测试案例:

#[test]
fn test1() {
let result = Solution::is_happy(19);
assert_eq!(result, true);
}

#[test]
fn test2() {
let result = Solution::is_happy(4);
assert_eq!(result, false);
}
#[test]
fn test3() {
let result = Solution::is_happy(123);
assert_eq!(result, false);
}

Kotlin:

方案:

internal class Solution {    fun isHappy(n: Int): Boolean {        var temp = n        val set: MutableSet<Int> = HashSet()        while (set.add(temp)) {            var value = 0            while (temp > 0) {                value += Math.pow(temp % 10.toDouble(), 2.0).toInt()                temp /= 10            }            temp = value        }        return temp == 1    }}

测试案例:

@Testfun test1() {val solution = Solution()val result = solution.isHappy(19)Assert.assertEquals(result, true)}@Testfun test2() {val solution = Solution()val result = solution.isHappy(4)Assert.assertEquals(result, false)}@Testfun test3() {val solution = Solution()val result = solution.isHappy(123)Assert.assertEquals(result, false)}

Python3:

方案:

class Solution:
def isHappy(self, n: int) -> bool:
s = set()
while(n not in s):
s.add(n)
v = 0
while (n > 0):
v += pow(n % 10, 2)
n = n // 10
n = v
return n == 1

测试案例:

def test_isHappy(self):
s = Solution()
self.assertEqual(s.isHappy(19), True )
def test2_isHappy(self):
s = Solution()
self.assertEqual(s.isHappy((4)), False)
def test3_isHappy(self):
s = Solution()
self.assertEqual(s.isHappy((123)), False)

Java:

方案:

class Solution {

public boolean isHappy(int n) {
Set<Integer> set = new HashSet<Integer>();

while (set.add(n))
{
int value = 0;
while (n > 0)
{
value += Math.pow(n % 10, 2);
n /= 10;
}
n = value;
}

return n == 1;
}
}

测试案例:

@Test
public void test1() {
Solution solution = new Solution();
boolean result = solution.isHappy(19);
Assert.assertEquals(result, true);
}

@Test
public void test2() {
Solution solution = new Solution();
boolean result = solution.isHappy(4);
Assert.assertEquals(result, false);
}

@Test
public void test3() {
Solution solution = new Solution();
boolean result = solution.isHappy(123);
Assert.assertEquals(result, false);
}

C++:

方案:

class HappyNumber {
public:
bool isHappy(int n) {
unordered_set<int> set;
while (set.find(n) == set.end())
{
set.insert(n);
int value = 0;
while (n > 0)
{
value += pow(n % 10, 2);
n /= 10;
}
n = value;
}

return n == 1;
}
};

测试案例:

TEST_METHOD(TestMethod1)
{
HappyNumber happyNumber;
Assert::AreEqual(true, happyNumber.isHappy(19));
}

TEST_METHOD(TestMethod2)
{
HappyNumber happyNumber;
Assert::AreEqual(false, happyNumber.isHappy(4));
}

TEST_METHOD(TestMethod3)
{
HappyNumber happyNumber;
Assert::AreEqual(false, happyNumber.isHappy(123));
}

C#:

方案:

public class Solution
{
public bool IsHappy(int n)
{
HashSet<int> hs = new HashSet<int>();
while(!hs.Contains(n))
{
hs.Add(n);
int v = 0;
while(n>0)
{
v += (int)Math.Pow(n % 10, 2);
n /= 10;
}
n = v;
}

return n == 1;
}
}

测试案例:

[TestMethod()]
public void Test1()
{
Solution solution = new Solution();
Assert.AreEqual(true, solution.IsHappy(19));
}

[TestMethod()]
public void Test2()
{
Solution solution = new Solution();
Assert.AreEqual(false, solution.IsHappy(4));
}

[TestMethod()]
public void Test3()
{
Solution solution = new Solution();
Assert.AreEqual(false, solution.IsHappy(123));
}
}

--

--