質問編集履歴
2
解決
test
CHANGED
File without changes
|
test
CHANGED
@@ -1,5 +1,65 @@
|
|
1
1
|
#質問文↓と実行しているコードに差があることでエラーが起こっていると思うのですが、whileループを終える条件は、n==1の時と、どの時ですか?
|
2
2
|
|
3
|
+
|
4
|
+
|
5
|
+
###解決したコード
|
6
|
+
|
7
|
+
```C++
|
8
|
+
|
9
|
+
|
10
|
+
|
11
|
+
class Solution {
|
12
|
+
|
13
|
+
public:
|
14
|
+
|
15
|
+
bool isHappy(int n) {
|
16
|
+
|
17
|
+
int remain;
|
18
|
+
|
19
|
+
int sum=0;
|
20
|
+
|
21
|
+
|
22
|
+
|
23
|
+
|
24
|
+
|
25
|
+
while(n>9){
|
26
|
+
|
27
|
+
while(n){
|
28
|
+
|
29
|
+
remain=n%10;
|
30
|
+
|
31
|
+
sum+=remain*remain;
|
32
|
+
|
33
|
+
n=n/10;
|
34
|
+
|
35
|
+
}
|
36
|
+
|
37
|
+
n=sum;
|
38
|
+
|
39
|
+
sum=0;
|
40
|
+
|
41
|
+
}
|
42
|
+
|
43
|
+
|
44
|
+
|
45
|
+
if(n==1)
|
46
|
+
|
47
|
+
return true;
|
48
|
+
|
49
|
+
else if(n==7)
|
50
|
+
|
51
|
+
return true;
|
52
|
+
|
53
|
+
else
|
54
|
+
|
55
|
+
return false;
|
56
|
+
|
57
|
+
}
|
58
|
+
|
59
|
+
};
|
60
|
+
|
61
|
+
```
|
62
|
+
|
3
63
|
```C++
|
4
64
|
|
5
65
|
Write an algorithm to determine if a number n is "happy".
|
1
改行
test
CHANGED
File without changes
|
test
CHANGED
@@ -6,7 +6,17 @@
|
|
6
6
|
|
7
7
|
|
8
8
|
|
9
|
-
A happy number is a number defined by the following process:
|
9
|
+
A happy number is a number defined by the following process:
|
10
|
+
|
11
|
+
Starting with any positive integer,
|
12
|
+
|
13
|
+
replace the number by the sum of the squares of its digits,
|
14
|
+
|
15
|
+
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.
|
16
|
+
|
17
|
+
|
18
|
+
|
19
|
+
Those numbers for which this process ends in 1 are happy numbers.
|
10
20
|
|
11
21
|
|
12
22
|
|