#質問文↓と実行しているコードに差があることでエラーが起こっていると思うのですが、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
回答3件
あなたの回答
tips
プレビュー