+ 2
Can anyone tell me how to optimise this code ?
17 Respuestas
+ 3
Shorter
+ 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. 🙂
+ 3
Denise Roßberg do normal methods decrease time complexity or the inbuilt methods?
+ 2
Anyone please answer?
+ 2
Optimise for what? Do you want it to be faster or shorter?
+ 2
Denise Roßberg you have too created this number
Genuine Stalwart thanks for sharing the information beforehand
+ 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.
+ 2
Genuine Stalwart yes
+ 2
And I don't want to use do while loop in this process
+ 2
7 is a happy number
+ 2
Denise Roßberg I have not learnt about streams but I can take one idea of that if condition. Thanks
+ 1
Atul
Can you explain what a happy number is?
+ 1
I tried a stream solution:
https://code.sololearn.com/c43ICk4WPJ0Q/?ref=app
A bit shorter but the code does not check the input.
+ 1
Atul Thanks. Now it works.
+ 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. ;)
+ 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.