teratail header banner
teratail header banner
質問するログイン新規登録

質問編集履歴

2

解決

2020/06/24 21:21

投稿

alizona
alizona

スコア126

title CHANGED
File without changes
body CHANGED
@@ -1,5 +1,35 @@
1
1
  #質問文↓と実行しているコードに差があることでエラーが起こっていると思うのですが、whileループを終える条件は、n==1の時と、どの時ですか?
2
+
3
+ ###解決したコード
2
4
  ```C++
5
+
6
+ class Solution {
7
+ public:
8
+ bool isHappy(int n) {
9
+ int remain;
10
+ int sum=0;
11
+
12
+
13
+ while(n>9){
14
+ while(n){
15
+ remain=n%10;
16
+ sum+=remain*remain;
17
+ n=n/10;
18
+ }
19
+ n=sum;
20
+ sum=0;
21
+ }
22
+
23
+ if(n==1)
24
+ return true;
25
+ else if(n==7)
26
+ return true;
27
+ else
28
+ return false;
29
+ }
30
+ };
31
+ ```
32
+ ```C++
3
33
  Write an algorithm to determine if a number n is "happy".
4
34
 
5
35
  A happy number is a number defined by the following process:

1

改行

2020/06/24 21:21

投稿

alizona
alizona

スコア126

title CHANGED
File without changes
body CHANGED
@@ -2,8 +2,13 @@
2
2
  ```C++
3
3
  Write an algorithm to determine if a number n is "happy".
4
4
 
5
- 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.
5
+ A happy number is a number defined by the following process:
6
+ Starting with any positive integer,
7
+ replace the number by the sum of the squares of its digits,
8
+ 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.
6
9
 
10
+ Those numbers for which this process ends in 1 are happy numbers.
11
+
7
12
  Return True if n is a happy number, and False if not.
8
13
  ```
9
14