Posts
Check if a number is a power of another number
- Get link
- Other Apps
Check if a number is a power of another number Input: x = 10, y = 1 Output: True x^0 = 1 Input: x = 10, y = 1000 Output: True x^3 = 1 Input: x = 10, y = 1001 Output: False Code: package sap; public class Power { public static void main(String[] args){ int x = 27, y = 729; int val = (int)Math.log(y)/ (int)Math.log(x); double res = Math.log(y)/Math.log(x); if(val == res){ System.out.println(x+" can be expressed as a power of "+y); } else{ System.out.println(x +" cannot be expressed as a power of "+y); } } } Output: 27 can be expressed as a power of 729
Reverse words in a given string
- Get link
- Other Apps
Given a String of length N reverse the whole string without reversing the individual words in it. Words are separated by dots. Code: package sap; public class ReverseWords { public static void main(String[] args){ String word = "I am done"; StringBuilder result = new StringBuilder(""); String[] arr = word.split("\\s"); for(int i=arr.length-1; i>=0; i--){ result.append(arr[i]); result.append(" "); } System.out.println(result.toString()); } } Output: done am I
Second Largest Element
- Get link
- Other Apps
Given an array of integers, our task is to write a program that efficiently finds the second largest element present in the array. Example: Input : arr[] = {12, 35, 1, 10, 34, 1} Output : The second largest element is 34. Code: package sap; public class SecondLargest { public static void main(String[] args){ int[] a = {89, 24, 75, 11, 23}; int max = Integer.MIN_VALUE, secondMax = Integer.MIN_VALUE; for(int i=0; i<a.length; i++){ if(a[i] > max){ secondMax = max; max = a[i]; } else if(a[i] > secondMax){ secondMax = a[i]; } } System.out.println("The second maximum element is "+secondMax); } } Output: The second maximum element is 75