The Programming Project

Sunday, January 8, 2023

Leet Code Roman to Integer

Roman numerals are represented by seven different symbols: IVXLCD and M.

Symbol       Value
I                   1
V                  5
X                 10
L                  50
C                 100
D                 500
M               1000

  For example, 2 is written as II in Roman numeral, just two ones added together. 12 is written as XII,       which is simply X + II. The number 27 is written as XXVII, which is XX + V + II.

 Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is   not IIII. Instead, the number four is written as IV. Because the one is before the five we subtract it making   four. The same principle applies to the number nine, which is written as IX. There are six instances where   subtraction is used:

  • I can be placed before V (5) and X (10) to make 4 and 9. 
  • X can be placed before L (50) and C (100) to make 40 and 90. 
  • C can be placed before D (500) and M (1000) to make 400 and 900.

 Given a roman numeral, convert it to an integer.

 

 Example 1:

Input: s = "III"
Output: 3
Explanation: III = 3.

 Example 2:

Input: s = "LVIII"
Output: 58
Explanation: L = 50, V= 5, III = 3.

 Example 3:

Input: s = "MCMXCIV"
Output: 1994
Explanation: M = 1000, CM = 900, XC = 90 and IV = 4.

 

 Constraints:

  • 1 <= s.length <= 15
  • s contains only the characters ('I', 'V', 'X', 'L', 'C', 'D', 'M').
  • It is guaranteed that s is a valid roman numeral in the range [1, 3999].
 Explanation:
The logic of the program is explained below with the example of MCMXCIV.
Take the value of each of the letters in the sequence:
1000 = M, 100 = C, 1000 = M, 10 = X, 100 = C, 1 = I, 5 = V
Keed adding the values in a variable. But for the second position onwards we
have check the difference of the value of the current position and the previous
position. If the difference is 4 or 9 or 40 or 90 or 400 or 900 then by the exception
rule we have to adjust the value.
For the example above, as 100-1000 = -900 ( i = 1 and i = 0) which is not under
exception rule we add 1000+100 = 1100
But for the next letter ('M') the value is 1000 ( i = 2 ) and 1000 - 100 = 900
( under exception rule), so instead of adding 1000 to 1100 we have to have add 900
to the value of the first letter ( since CM is forming a single value). For this
we need to subtract the value of the current letter (M = 1000) and the previous
letter ( C = 100 ) from the sum of 1000+100+1000 = 2100 and add 900.
Which gives 2100-1000 - 100 + 900 = 1900.


PYTHON CODE

class Solution(object):

    def romanToInt(self, s):
        temp = 0
        for i in range(len(s)):
            self.output += self.value[self.position(s[i])]
            #print ("BEFORE ADJUSTMENT",self.output)
            if i > 0:
                temp = (self.value[self.position(s[i])] -
                        self.value[self.position(s[i - 1])])
            if temp == 4 or temp == 9 or temp == 40 or temp == 90 or temp == 400 or temp == 900:
                self.output = self.output - self.value[self.position(
                    s[i - 1])] - self.value[self.position(s[i])] + temp
            #print ("AFTER ADJUSTMENT",self.output)
        return self.output

    def position(self, symb):
        counter = 0
        while symb != self.symbol[counter]:
            counter += 1
        return (counter)

    symbol = ['I', 'V', 'X', 'L', 'C', 'D', 'M']
    value = [1, 5, 10, 50, 100, 500, 1000]
    output = 0


obj = Solution()
s = str(input("Enter a valid roman numeral in range(1,3999):"))
print(obj.romanToInt(s))

ICSE Java Programming Spy Number 2017 Q5 Solved

ICSE Java Programming Spy Number  2017 Q5  Solved

Write a program to accept a number and check and display whether it is a spy number or not. (A number is spy if the sum of its digits equals the product of its digits.)
Example : consider the number 1124.
Sum of the digits = 1 + 1+ 2 + 4 = 8
Product of the digits = 1×1 x 2 x 4 = 8
Thus 1124 is a Spy Number

Java Code

import java.util.Scanner;

public class ICSEJava {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int sum_of_digits = 0;
        int product_of_digits = 1;
        int number, digit, temp;
        System.out.println("Enter a positive integer:");
        number = in.nextInt();
        temp = number;
        while (temp > 0) {
            digit = temp % 10;
            temp = (int) (temp / 10);
            sum_of_digits += digit;
            product_of_digits *= digit;
        }
        if (sum_of_digits == product_of_digits)
            System.out.println(number + " is a spy number.");
        else
            System.out.println(number + " is not a spy number.");
    }
}

Python Code

sum_of_digits = 0
product_of_digits = 1
number = int(input("Enter a postive integer:"))
temp = number
while temp > 0:
    digit = temp%10
    temp = int(temp/10)
    sum_of_digits += digit
    product_of_digits *= digit
if sum_of_digits == product_of_digits:
    print(number," is a spy number.")
else:
    print(number," is not a spy number.")

ICSE Java Programming Strings 2022 Q7 SPECIMEN PAPER Solved

ICSE Java Programming Strings  2022 Q7 SPECIMEN PAPER Solved

Question 7
Define a class to accept and store 10 strings into the array and print the strings with even number of characters.


import java.util.Scanner;

public class ICSEJava {
    public static void main(String[] args) {
        EvenCharacters obj = new EvenCharacters();
        obj.inputString();
        obj.charCounter();
    }
}

class EvenCharacters {
    public void charCounter() {
        System.out.println("Strings with even number of characters:");
        for (int i = 0; i < 10; i++) {
            this.char_count = 0;
            for(int j =0; j<this.message[i].length();j++)    {
                if(this.message[i].charAt(j) == ' ')
                    continue;
                else
                    this.char_count++;
                }
            if (this.char_count%2 == 0)
                System.out.println(this.message[i]);
            }      
    }

    public void inputString() {
        Scanner in = new Scanner(System.in);
        System.out.println("Enter the strings one by one:");
        for (int i = 0; i < 10; i++) {
            System.out.println("Enter a string:");
            this.message[i] = in.nextLine();
        }
        in.close();
    }

    EvenCharacters() {
        this.message = new String[10];
        this.char_count = 0;
    }

    private int char_count;
    private String[] message;
}

ICSE Java Programming palindrome 2022 Q6 SPECIMEN PAPER Solved

ICSE Java Programming Palindrome strings  2022 Q6 SPECIMEN PAPER Solved

Define a class to accept a string, convert it into lowercase and check whether the string is a palindrome or not. A palindrome is a word which reads the same backward as forward.

Example: madam, racecar


import java.util.Scanner;

public class ICSEJava {
    public static void main(String[] args) {
        Palindrome obj = new Palindrome();
        obj.inputString();
        obj.checkPalindrome();
    }
}

class Palindrome {
    public void checkPalindrome() {
        for (int i = 0; i < this.message.length(); i++) {
            if (this.message.charAt(i) != this.message.charAt(this.message.length() - 1 - i)) {
                flag = false;
                break;
            } else
                continue;
        }
        if (flag)
            System.out.println("Entered word is a palindrome:" + this.message);
        else
            System.out.println("Entered word is not a palindrome.");
    }

    public void inputString() {
        Scanner in = new Scanner(System.in);
        System.out.println("Enter the word:");
        this.message = in.nextLine();
        this.message = this.toLowerCase(message);
        in.close();
    }

    private String toLowerCase(String msg) {
        String temp = "";
        for (int i = 0; i < msg.length(); i++) {
            if (msg.charAt(i) >= 'A' && msg.charAt(i) <= 'Z') {
                temp += (char) (msg.charAt(i) + 32);
            } else
                temp += (msg.charAt(i));
        }
        return temp;
    }

    Palindrome() {
        this.message = "";
        this.flag = true;
    }

    private boolean flag;
    private String message;
}

ICSE Java Programming Equal and Uppercase strings 2022 Q5 SPECIMEN PAPER Solved

ICSE Java Programming Equal and Uppercase strings  2022 Q4 SPECIMEN PAPER Solved

Question 5

Define a class to accept two strings, convert them into uppercase, check and display whether two strings are equal or not, if the two strings are not equal, print the string with the highest length or print the message both the strings are of equal length.




import java.util.Scanner;

public class ICSEJava {
    public static void main(String[] args) {
        StringCheck obj = new StringCheck();
        obj.inputString();
        obj.display();

    }
}

class StringCheck {
    public void display() {
        if (this.isequal)
            System.out.println("Both the strings are equal");
        else
            System.out
                    .println(" String with highest length :"
                            + (this.message_first.length() < this.message_second.length()
                                    ? this.message_second
                                    : this.message_first));
    }

    public void inputString() {
        Scanner in = new Scanner(System.in);
        System.out.println("Enter the first string:");
        this.message_first = in.nextLine();
        System.out.println("Enter the second string:");
        this.message_second = in.nextLine();
        System.out.println("OUTPUT:");
        System.out.println(this.toUpperCase(this.message_first));
        System.out.println(this.toUpperCase(this.message_second));
        if (!this.message_first.equals(this.message_second))
            this.isequal = false;
        in.close();
    }

    private String toUpperCase(String msg) {
        String temp = "";
        for (int i = 0; i < msg.length(); i++) {
            if (msg.charAt(i) >= 'a' && msg.charAt(i) <= 'z') {
                temp += (char) (msg.charAt(i) - 32);
            } else
                temp += (msg.charAt(i));
        }
        return temp;
    }

    StringCheck() {
        this.message_first = "";
        this.message_second = "";
        this.isequal = true;
    }

    private boolean isequal;
    private String message_first;
    private String message_second;

}

Thursday, January 5, 2023

ICSE Java Programming Array of Numbers 2022 Q4 SPECIMEN PAPER Solved

ICSE Java Programming Array of Numbers 2022 Q4 SPECIMEN PAPER Solved

Question 4

Define a class to declare an array of size 20 of double datatype, accept the elements into the array and perform the following:

Calculate and print the sum of all the elements.

Calculate and print the highest value of the array.



Python Code (Without using class)

_array = []
array_size = 20
max_element = 0.0
sum = 0.0
print("Enter the elements in the array:")
for i in range(array_size):
    print("Enter the element at the position:",(i+1))
    _array.append(float(input()))
    sum += _array[i]
    if max_element < _array[i]:
        max_element = _array[i]
print("Sum of all the elements is ",sum)
print("Maximum element in the array ",max_element)

JAVA CODE

import java.util.Scanner;

public class ICSEJava {
    public static void main(String[] args) {
        Array obj = new Array();
        obj.inputArray();
        obj.sumOfElements();
        obj.maxElement();
    }
}

class Array {
    public void inputArray() {
        Scanner in = new Scanner(System.in);
        System.out.println("Enter the elements of the array:");
        for (int i = 0; i < this.array_size; i++) {
            System.out.println("Enter the element:");
            this.array[i] = in.nextDouble();
        }
        in.close();
    }

    public void maxElement() {
        for (int i = 0; i < this.array_size; i++)
            if (this.max_element < this.array[i])
                this.max_element = this.array[i];
        System.out.println("Maximum element in the array " + this.max_element);
    }

    public void sumOfElements() {
        for (int i = 0; i < this.array_size; i++)
            this.sum += this.array[i];
        System.out.println("Sum of all the elements is " + this.sum);
    }

    Array() {
        this.sum = 0;
        this.max_element = 0;
    }

    private double[] array = new double[20];
    private double sum;
    private double max_element;
    private static int array_size = 20;
}

Wednesday, January 4, 2023

ICSE Java Programming Character Array 2022 Q3 Specimen Paper Solved

  ICSE Java Programming Character Array  2022 Q3 Solved


PYTHON CODE

char_array = []
array_size = 10
upper_counter = 0
vowel_counter = 0
vowel =['A', 'E', 'I', 'O', 'U' ]
print("Enter the characters in the array:")
for i in range(array_size):
    print("Enter the element at the position:",(i+1))
    char_array.append(str(input()))
for i in range(array_size):
    if char_array[i] >= 'A' and char_array[i] <= 'Z':
        print(char_array[i]," is an upper case character.")
        upper_counter +=1
for i in range(array_size):
    for j in range(5):
        if char_array[i] == vowel[j] or str(char_array[i]).upper() == vowel[j]:
            print(char_array[i]," is an vowel.")
            vowel_counter +=1
print("Total number of uppercase characters =",upper_counter)
print("Total number of vowels =",vowel_counter)


JAVA CODE

import java.util.Scanner;

public class ICSEJava2022 {
    public static void main(String[] args) {
        characterArray obj = new characterArray();
        obj.input();
        obj.display();
    }
}

class characterArray {
    public void display() {
        for (int i = 0; i < this.array_size; i++) {
            if (this.char_array[i] >= 65 && this.char_array[i] <= 90) {
                System.out.println(this.char_array[i] + " is an upper case character.");
                this.upper_counter++;
            }
            for (int j = 0; j < 5; j++)
                if (this.char_array[i] == this.vowel[j] || (char) (this.char_array[i] - 32) == this.vowel[j]) {
                    System.out.println(this.char_array[i] + " is an vowel.");
                    this.vowel_counter++;
                }
        }
        System.out.println("Total number of upper case characters =" + this.upper_counter);
        System.out.println("Total number of vowels =" + this.vowel_counter);
    }

    public void input() {
        Scanner in = new Scanner(System.in);
        System.out.println("Enter the characters in the array:");
        for (int i = 0; i < this.array_size; i++) {
            System.out.println("Enter the element at the position " + (i + 1));
            this.char_array[i] = in.next().charAt(0);
        }
        in.close();
    }

    characterArray() {
        this.array_size = 10;
        this.char_array = new char[this.array_size];
        this.upper_counter = 0;
        this.vowel_counter = 0;
    }

    private char[] char_array;
    private static char[] vowel = { 'A', 'E', 'I', 'O', 'U' };
    private static int array_size;
    private int upper_counter;
    private int vowel_counter;

}