Can anyone tell me how to optimise this code ? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 2
31st May 2021, 4:14 PM
Atul [Inactive]
17 Answers
+ 3
Shorter
31st May 2021, 5:01 PM
Atul [Inactive]
+ 3
Denise Roßberg In number theory, a happy number is a number which eventually reaches 1 when replaced by the sum of the square of each digit. Source: https://en.m.wikipedia.org/wiki/Happy_number I once tried to create some codes of such sequences, thus I found this. 🙂
31st May 2021, 5:13 PM
Genuine Stalwart
Genuine Stalwart - avatar
+ 3
Denise Roßberg do normal methods decrease time complexity or the inbuilt methods?
31st May 2021, 7:26 PM
Atul [Inactive]
+ 2
Anyone please answer?
31st May 2021, 4:40 PM
Atul [Inactive]
+ 2
Optimise for what? Do you want it to be faster or shorter?
31st May 2021, 4:58 PM
Ore
Ore - avatar
+ 2
Denise Roßberg you have too created this number Genuine Stalwart thanks for sharing the information beforehand
31st May 2021, 5:17 PM
Atul [Inactive]
+ 2
Atul Genuine Stalwart 1 year ago! Feels like ages for me. lol But I would say my isHappy() method is fine. Maybe there would be also a way to solve it with streams but I don't think that you can do it shorter.
31st May 2021, 5:24 PM
Denise Roßberg
Denise Roßberg - avatar
31st May 2021, 5:26 PM
Atul [Inactive]
+ 2
And I don't want to use do while loop in this process
31st May 2021, 5:34 PM
Atul [Inactive]
+ 2
7 is a happy number
31st May 2021, 6:50 PM
Atul [Inactive]
+ 2
Denise Roßberg I have not learnt about streams but I can take one idea of that if condition. Thanks
31st May 2021, 7:01 PM
Atul [Inactive]
+ 1
Atul Can you explain what a happy number is?
31st May 2021, 5:08 PM
Denise Roßberg
Denise Roßberg - avatar
+ 1
I tried a stream solution: https://code.sololearn.com/c43ICk4WPJ0Q/?ref=app A bit shorter but the code does not check the input.
31st May 2021, 6:38 PM
Denise Roßberg
Denise Roßberg - avatar
+ 1
Atul Thanks. Now it works.
31st May 2021, 6:59 PM
Denise Roßberg
Denise Roßberg - avatar
+ 1
Here you find more about streams: https://www.baeldung.com/java-8-streams (String.chars() returns an IntStream.) Conclusion: using inbuilt methods can shorten your code but not always. ;)
31st May 2021, 7:16 PM
Denise Roßberg
Denise Roßberg - avatar
+ 1
I would say it depends on your code or the problem you want to solve. But I think inbuilt methods do for what they are built for in an effective way. And they can simplify your code. You don't need to write an own method if you already have an inbuilt method which does the same.
31st May 2021, 7:56 PM
Denise Roßberg
Denise Roßberg - avatar