Sunday, December 13, 2020

Print name of each digit of a number in Java

 Challenge is to write a method to print the passed number using words for each of the digits. If the number is negative then print "Invalid Value". 

I simply used the String manipulations in Java to resolve this issue with aid of a Switch statement to identify each digit and get the corresponding name of the digit.

Below is my working solution and I hope it is helpful.

public class NumberToWords {
public static void numberToWords(int number){
String resultString = "";
if(number < 0){
resultString = "Invalid Value";
}else{
String numberString = String.valueOf(number);

for(int i=0; i<numberString.length(); i++){
int currentNumber = Character.getNumericValue
(numberString.charAt(i));

resultString = resultString +
getNameOfNumber(currentNumber) + " ";
}
}
System.out.println(resultString);
}

public static String getNameOfNumber(int num){
String numberName = "";
switch (num){
case 0 :
numberName = "Zero";
break;
case 1:
numberName = "One";
break;
case 2:
numberName = "Two";
break;
case 3:
numberName = "Three";
break;
case 4:
numberName = "Four";
break;
case 5:
numberName = "Five";
break;
case 6:
numberName = "Six";
break;
case 7:
numberName = "Seven";
break;
case 8:
numberName = "Eight";
break;
case 9:
numberName = "Nine";
break;
default:
numberName = "Invalid";
break;
}
return numberName;
}
}



How to find the greatest common divisor of two integers in java?

This was another coding challenge I came across while practising online. Little bit tricky, however, I found a solution (I say 'a' solution because there can be alternative ways to do the same) for it. 

So, what are we suppose to do here?

  • A method accepts two integer parameters and we need to find the highest divisible integer by which both the numbers could be divided without a remainder.
  • If either one of the given number is less than 10 then the method should return -10 indicating invalid input.
here is my solution and I hope it's helpful.

public class GreatestCommonDivisor {
public static int getGreatestCommonDivisor(int first, int second){
int greatestCommonDivisor = -1;

if(first >= 10 && second >= 10){
int smallerNumber = first < second ? first : second;

for(int i = smallerNumber ; i >= 1 ; i--){
if( (first % i == 0) && (second % i == 0)){
greatestCommonDivisor = i;
break;
}else{
continue;
}
}
}
return greatestCommonDivisor;
}
}

Java program to get only the even digit sum of a given integer

 Yet another coding challenge I came across and here is the challenge ; 

you are given an Integer number

return - 1 if it is a negative number

if not, calculate the sum of all the even digits of the given number

    e.g:- 1658 is given then sum = 6 + 8 which is 14

below is my solution and I hope it helps

public class EvenDigitSum {
public static int getEvenDigitSum(int number){
int sumOfEvenDigits = 0;

if(number < 0){
sumOfEvenDigits = -1;
}else{
int lengthOfNumber = String.valueOf(number).length();

for(int i=0 ; i< lengthOfNumber ; i++){
int currentNumber = Character.getNumericValue(String.valueOf(number).charAt(i));
if(currentNumber % 2 == 0){
sumOfEvenDigits += currentNumber;
}else{
continue;
}
}
}
return sumOfEvenDigits;
}
}


How to check a given number is a palindrome in Java ?

This is another online coding challenge I came across recently to which I found a simple solution with the use of String and StringBuffer in java. 

Let me explain the challenge here,

  • A given number is a palindrome when reversed is equal to the original number (e.g : 121, 45654,1001)
  • If the given number is a palindrome, then return true else return false
In my solution I basically convert the integer number to a string in order to reverse the number, Unfortunately java doesn't have a reverse method in String class (it's java 11 that I'm working with). However, StringBuilder has a reverse method to which a String needs to be parsed. So, here's what I'm doing.

get the Integer number --> convert to String --> convert to StringBuilder --> reverse the string --> convert back to String --> convert the string back to number --> store it in a new int variable --> compare with the original number --> return true if matches or return false unless otherwise

why do I use Math.abs() ?

This is simply to handle any negative numbers. for an instance, -232 is a palindrome but if we straight away convert it to string this will reverse the string as 232- which ends up with an invalid integer. To handle this, I have considered the absolute value by using Math.abs() function to only get the absolute value of the given number.

find my solution as below

public class NumberPalindrome {
public static boolean isPalindrome(int number){
boolean result = false;
number = Math.abs(number);
int reversedNumber = Integer.parseInt(new StringBuilder(String.valueOf(number)).reverse().toString());

if(number == reversedNumber){
result = true;
}
return result;
}
}

Simple Java program to calculate the sum of all the digits of a number

 I just came across a simple yet an interesting challenge when I was attempting some online coding practices and thought to share it with you. Firstly would like to state that there can be many ways to separate each digit of the given number but I have used the most convenient way by converting it to String and processing.

Let me explain you the challenge.

  • An integer number is given and it should be at least a two digit number (15, 896 etc but not 9). Return -1 if this is not met.
  • If the above condition is met, then sum up all the digits of the number and return.
find my solution as below

public class DigitSum {
public static int sumDigits(int number){
int sum = 0;
if(number >= 10){
int numOfDigits = String.valueOf(number).length();

for(int i=0; i<numOfDigits ; i++){
sum += Character.getNumericValue(String.valueOf(number).charAt(i));
}
}else{
sum = -1;
}
return sum;
}
}

Thursday, December 3, 2020

How to validate a username with the aid of regular expressions in Java?

 I find regular expressions interesting because if you got the right idea of when and how to use them, it will help you to reduce lines of code and would save time as well. 

In the below example, I am going to demonstrate on how to validate a simple username (assume username entered in a System during the Sign Up process) .

Rules

  • The username consists of 8 to 30 characters inclusive. If the username consists of less than 8 or greater than 30 characters, then it is an invalid username.
  • The username can only contain alphanumeric characters and underscores (_). Alphanumeric characters describe the character set consisting of lowercase characters [a-z] uppercase character [A - Z], and digits [0 - 9].
  • The first character of the username must be an alphabetic character, i.e., either lowercase character [a - z] or uppercase character [A -Z]

I am going to use the stdin to get inputs and stdout to print the results. The first input will indicate how many input strings (usernames) are going to be validated and subsequent inputs will indicate each username to be validated.

import java.util.Scanner;

class Validator {
public static final String regularExpression = "^[a-zA-Z][a-zA-Z0-9|_]{7,29}$";
}

public class UsernameValidator{
public static void main(String[] args) {
Scanner scanner = new Scanner (System.in);
int numOfUserNames = Integer.parseInt(scanner.nextLine());

while(numOfUserNames > 0){

String userName = scanner.nextLine();

if(userName.matches(Validator.regularExpression)){
System.out.println("Valid Username");
}else{
System.out.println("Invalid Username");
}
numOfUserNames--;
}
}
}

Input / Output:


5
Amanda
Invalid Username
Cassandra
Valid Username
Amelia_2134
Valid Username
1Jessica231
Invalid Username
Emma_654424
Valid Username

Explanation to the regular expression I used above

^ [a-zA-Z] --> indicates the beginning of the string which should contain a-z or A-Z (only alphabets)
[a-zA-Z-0-9_] --> indicates the string starting from the second character of the username which can consists of alphabets, digits or _. No Symbols allowed here. 
{7,29}  --> indicates the length of the username starting from the second character. which is 7 to 29 character long.

A great approach to practice regular expressions is to create your own simple java programs and imagine various types of validations that could perform in a System, and crack them with the aid of Regular expressions instead of using String manipulations or conditional blocks to resolve the challenges.




Sunday, November 29, 2020

How to check two strings have a common substring in Java?

Given two strings, determine if they share a common substring. A substring may be as small as one character.

For example, the words "j", "and", "jug" share the common substring 'j' The words "or" and "fit" do not share a substring.

Input Format

The first line contains a single integer , the number of test cases.

The following  pairs of lines are as follows:

  • The first line contains string s1
  • The second line contains string s2

Output Format

For each pair of strings, return YES or NO.

Sample Input

2

she

saw

dress

pat

Sample Output

YES

NO

There is a basic approach for this challenge which by using a nested for loop we can detect common substrings (outer for loop traverse through s1 and the inner for loop traverse through s2. For each character in s1, each character of s2 will be matched and if same character is found , return YES and break) , however this solution is not efficient because its complexity is O(n^2).

Below approach is more efficient in which I store each character of the s1 string in a Set and then traverse through s2 String to find whether the above set contains any of the character of s2. 

Find my solution below.

static String twoStrings(String s1, String s2) {
String result="NO";
Set<Character> set1 = new HashSet<Character>();

for (char s : s1.toCharArray()){
set1.add(s);
}

for(int i=0;i<s2.length();i++){
if(set1.contains(s2.charAt(i))){
result = "YES";
break;
}
}
return result;
}




Finding whether a given string has balanced parenthesis using Java Stack

 Challenge: Given a string in the stdin with a set of parenthesis [{[()]}] and the stdout should print either true or false based on whether the parenthesis are matched or not

e.g: 

{} --> true

{[()]} -->true

{[}] -- > false

Solution : I am going to use a Java Stack to resolve this problem following the below approach.

1.use stdin to read the input

2.iterate reading from stdin while there are more inputs

3.store each string in a variable and validate

4.validation >> 

    a. loop through each character of the string

    b.If current character is ( OR { OR [ then add the value to the Stack

    c.If the current character is ) OR } OR ] then pop a value from the Stack and compare it with the current character

   d. if matches then result is true , continue ; else set result as false 

Below is the coding

-----------------------------------------------------------------------------------------------------------------------------

package com.hackerrank;

import java.util.Scanner;
import java.util.Stack;

public class Main {

/**
* Main method
* @param args
*/
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in); //stdin
while(scanner.hasNext()){ //reading continues till stdin has more inputs
String input = scanner.nextLine(); //read String
System.out.println(checkBalancedLine(input)); //validate and print result
}
}

/**
* This method validates the string with balanced paranthesis
* @param inputLine
* @return true or false
*/
public static boolean checkBalancedLine(String inputLine){
boolean balanced =false;

Stack<String> stringStack = new Stack<String>();

for(int i=0;i<inputLine.length();i++){
if((inputLine.charAt(i)=='(') || (inputLine.charAt(i)=='{') || (inputLine.charAt(i)=='[')) { //if the character is ([{ then add to the stack
stringStack.add(String.valueOf(inputLine.charAt(i)));
}
if((inputLine.charAt(i)==')') || (inputLine.charAt(i)=='}') || (inputLine.charAt(i)==']')) { //if the character is )]} then pop the stack and compare the ith value against the popped value
if(!stringStack.isEmpty()) {
String poppedString = stringStack.pop();
if (inputLine.charAt(i) == ')' && poppedString.equalsIgnoreCase("(")) {
balanced = true;
} else if (inputLine.charAt(i) == ']' && poppedString.equalsIgnoreCase("[")) {
balanced = true;
} else if (inputLine.charAt(i) == '}' && poppedString.equalsIgnoreCase("{")) {
balanced = true;
} else {
balanced = false;
}
}
}
}
return balanced;
}
}

   Console