Skip to content

Commit

Permalink
Reverse number when ListNode or int[]
Browse files Browse the repository at this point in the history
  • Loading branch information
srinivasvadige committed Nov 10, 2024
1 parent b92d592 commit 46626de
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 5 deletions.
30 changes: 30 additions & 0 deletions BasicPrograms/PalindromeOrReverseNumber.java
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,27 @@ public static void main(String[] args) {
System.out.println("Reverse using STRING BUILDER REVERSE => " + stringBuilderReverse(n));
System.out.println("isPalindrome: " + isPalindrome(n));
System.out.println("isPalindromeStringApproach: " + isPalindromeStringApproach(n));


System.out.println("ListNode approach --------------------------------------- ");
ListNode l1 = new ListNode(2, new ListNode(4, new ListNode(3)));

int n1 = 0;
for(ListNode trav=l1; trav!=null; trav=trav.next){ // ----- normal sequence
n1 = n1*10 + trav.val;
}
System.out.println(n1); // 243

n1 = 0;
for(ListNode trav=l1; trav!=null; trav=trav.next){ // ----- reverse sequence
int zeros = (int) Math.log10(n1==0?1:n1)+1; // Math.log10(0) is -Infinity and (int)Math.log10(0) is -2147483648
// or zeros = String.valueOf(n1).length();
int mul = (int) Math.pow(10, zeros);
if(n1 == 0)
mul = 1;
n1 = trav.val*mul + n1;
}
System.out.println(n1); // 342
}

// reversing using %10 and /10 concept
Expand Down Expand Up @@ -70,4 +91,13 @@ public static boolean isPalindromeStringApproach(int x) {
return new StringBuilder(String.valueOf(x)).reverse().toString().equals(String.valueOf(x));
}

@SuppressWarnings("unused")
private static class ListNode {
int val;
ListNode next;
ListNode() {}
ListNode(int val) { this.val = val; }
ListNode(int val, ListNode next) { this.val = val; this.next = next; }
}

}
10 changes: 5 additions & 5 deletions DataStructures/BinaryTreeNode.java
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
package DataStructures;

public class BinaryTreeNode {
int val;
BinaryTreeNode left, right;
BinaryTreeNode() {}
BinaryTreeNode(int val) { this.val = val; }
BinaryTreeNode(int val, BinaryTreeNode left, BinaryTreeNode right) {
public int val;
public BinaryTreeNode left, right;
public BinaryTreeNode() {}
public BinaryTreeNode(int val) { this.val = val; }
public BinaryTreeNode(int val, BinaryTreeNode left, BinaryTreeNode right) {
this.val = val;
this.left = left;
this.right = right;
Expand Down

0 comments on commit 46626de

Please sign in to comment.