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

Q&A

解決済

3回答

1900閲覧

whileループを終えるときの条件がわからない。

alizona

総合スコア126

C++

C++はC言語をもとにしてつくられた最もよく使われるマルチパラダイムプログラミング言語の1つです。オブジェクト指向、ジェネリック、命令型など広く対応しており、多目的に使用されています。

0グッド

1クリップ

投稿2020/06/24 02:26

編集2020/06/24 21:21

0

1

#質問文↓と実行しているコードに差があることでエラーが起こっていると思うのですが、whileループを終える条件は、n==1の時と、どの時ですか?

###解決したコード

C++

1 2class Solution { 3public: 4 bool isHappy(int n) { 5 int remain; 6 int sum=0; 7 8 9 while(n>9){ 10 while(n){ 11 remain=n%10; 12 sum+=remain*remain; 13 n=n/10; 14 } 15 n=sum; 16 sum=0; 17 } 18 19 if(n==1) 20 return true; 21 else if(n==7) 22 return true; 23 else 24 return false; 25 } 26};

C++

1Write an algorithm to determine if a number n is "happy". 2 3A happy number is a number defined by the following process: 4Starting with any positive integer, 5replace the number by the sum of the squares of its digits, 6and repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not include 1. 7 8Those numbers for which this process ends in 1 are happy numbers. 9 10Return True if n is a happy number, and False if not.

イメージ説明

###コード

C++

1class Solution { 2public: 3 bool isHappy(int n) { 4 5 bool isone=false; 6 bool ishun=false; 7 bool isten=false; 8 int one; 9 int ten; 10 int hun; 11 12 while(n!=1){ //←この条件を何にすべきかわかりません。 13 isone=false; 14 ishun=false; 15 isten=false; 16 17 if(n<10) 18 isone=true; 19 20 else if(n<100){ 21 isone=false; 22 isten=true; 23 24 }else if(n>99){ 25 isten=false; 26 ishun=true; 27 } 28 29 if(isone){ 30 one=n; 31 n=one*one; 32 33 }else if(isten){ 34 ten=n/10; 35 one=n-ten*10; 36 37 n=ten*ten+one*one; 38 }else if(ishun){ 39 hun=n/100; 40 ten=(n-hun*100)/10; 41 one=n-hun*100+ten*10; 42 43 n=hun*hun+ten*ten+one*one; //←エラーはここにあります。 44 } 45 } 46 if(n==1) 47 return true; 48 else 49 return false; 50 } 51};

###エラー

C++

1Line 66: Char 22: runtime error: signed integer overflow: 231813 * 231813 cannot be represented in type 'int' (solution.cpp) 2SUMMARY: UndefinedBehaviorSanitizer: undefined-behavior prog_joined.cpp:75:22

気になる質問をクリップする

クリップした質問は、後からいつでもMYページで確認できます。

またクリップした質問に回答があった際、通知やメールを受け取ることができます。

yumetodo

2020/06/24 02:43

とりあえずintじゃなくてuint64_tに変えてみてはどうですかね?エラー文そのものは型の大きさが足らんって言ってるので
alizona

2020/06/24 04:16

ありがとうございます。 uint64_t ですね。初めて見ました。 使い方等理解したのですが、 私の解く問題の関数の引数の型は予めintに指定されています。 英語が読めてなくて、whle loopの条件をどうしていいかわかっていません。 そのため桁数が大きくなるまでループして、今回のエラーが起こっています。
guest

回答の取得に失敗しました

15分調べてもわからないことは
teratailで質問しよう!

ただいまの回答率
85.25%

質問をまとめることで
思考を整理して素早く解決

テンプレート機能で
簡単に質問をまとめる

質問する

関連した質問