aboutsummaryrefslogtreecommitdiff
path: root/happy_number.cpp
diff options
context:
space:
mode:
authorjack <[email protected]>2024-06-14 13:13:15 -0600
committerjack <[email protected]>2024-06-14 13:13:15 -0600
commitd343a3b18dbaca9297d4f7b2280c4a16f0a5c8aa (patch)
tree96df922dae2a5073d9a50ea70c7aae6aa37e3ebe /happy_number.cpp
downloadleetcode-d343a3b18dbaca9297d4f7b2280c4a16f0a5c8aa.tar.gz
leetcode-d343a3b18dbaca9297d4f7b2280c4a16f0a5c8aa.zip
initial
Diffstat (limited to 'happy_number.cpp')
-rw-r--r--happy_number.cpp37
1 files changed, 37 insertions, 0 deletions
diff --git a/happy_number.cpp b/happy_number.cpp
new file mode 100644
index 0000000..e946b96
--- /dev/null
+++ b/happy_number.cpp
@@ -0,0 +1,37 @@
+#include "leetcode.h"
+
+class Solution {
+public:
+ bool isHappy(int n) {
+ int slow, fast;
+ slow = fast = n;
+ do {
+ slow = square(slow);
+ for (int i = 0; i < 2; i++)
+ fast = square(fast);
+ } while (slow != fast);
+ if (slow == 1)
+ return 1;
+ else
+ return 0;
+ }
+
+private:
+ int square(int n) {
+ int num = 0, tmp;
+ while (n) {
+ tmp = n % 10;
+ num += tmp * tmp;
+ n /= 10;
+ }
+ return num;
+ }
+};
+
+int main() {
+ Solution obj;
+ if (obj.isHappy(19))
+ cout << "true";
+ else
+ cout << "false";
+}