File tree Expand file tree Collapse file tree 2 files changed +57
-0
lines changed
java/Fast and Slow Pointers Expand file tree Collapse file tree 2 files changed +57
-0
lines changed Original file line number Diff line number Diff line change
1
+ public class HappyNumber {
2
+ public boolean happyNumber (int n ) {
3
+ int slow , fast ;
4
+ slow = fast = n ;
5
+ while (true ) {
6
+ slow = getNextNum (slow );
7
+ fast = getNextNum (getNextNum (fast ));
8
+ if (fast == 1 ) return true ;
9
+ // If the fast and slow pointers meet, a cycle is detected.
10
+ // Hence, 'n' is not a happy number.
11
+ else if (fast == slow ) return false ;
12
+ }
13
+ }
14
+
15
+ private int getNextNum (int x ) {
16
+ int nextNum = 0 ;
17
+ while (x > 0 ) {
18
+ // Extract the last digit of 'x'.
19
+ int digit = x % 10 ;
20
+ // Truncate (remove) the last digit from 'x' using floor
21
+ // division.
22
+ x /= 10 ;
23
+ // Add the square of the extracted digit to the sum.
24
+ nextNum += Math .pow (digit , 2 );
25
+ }
26
+ return nextNum ;
27
+ }
28
+ }
Original file line number Diff line number Diff line change
1
+ import DS .ListNode ;
2
+
3
+ /*
4
+ // Definition of ListNode:
5
+ class ListNode {
6
+ public int val;
7
+ public ListNode next;
8
+ public ListNode(int val) { this.val = val; }
9
+ public ListNode(int val, ListNode next) {
10
+ this(val);
11
+ this.next = next;
12
+ }
13
+ }
14
+ */
15
+
16
+
17
+ public class LinkedListMidpoint {
18
+ public ListNode linkedListMidpoint (ListNode head ) {
19
+ ListNode slow , fast ;
20
+ slow = fast = head ;
21
+ // When the fast pointer reaches the end of the list, the slow
22
+ // pointer will be at the midpoint of the linked list.
23
+ while (fast != null && fast .next != null ) {
24
+ slow = slow .next ;
25
+ fast = fast .next .next ;
26
+ }
27
+ return slow ;
28
+ }
29
+ }
You can’t perform that action at this time.
0 commit comments