Skip to main content

Posts

Showing posts from March, 2020

Convert to Roman Number

The website leetcode has quite a huge collection of difficult coding questions. As they say, start small. I tried a easy question (medium according to the site). Converting a number to Roman numerals. We all know that in Roman number system M - 1000 D - 500 C - 100 L - 50 X - 10 V - 5 I - 1 And     CD is 400     CM is 900     XL is 40     XC is 90     IV is 4     IX is 9 If I look at many examples, it appears that 4 is never IIII, but IV. Similarly 40 is XL. So I think a symbol never appears 4 times, instead you take the next symbol and subtract it (by placing a symbol to its left). So here is question. And my algorithm was brute force - it was OK, because the question said that the numbers are between 1 to 3999. What I did was     Find the number of thousands and place M for each thousand     Number is number modulo 1000 Find the number of hundreds If the hundreds is 9  - place a CM for this If the hundreds is 4 - place a CD for this If hundred is mor

Covariant methods

Normally when we override a function(method) in a derived class, this overriding function must have the same signature as the function in base class. But in Java, the overriding method can have a different return type provided this return type is the sub-class of return type in overridden method. Such methods are called Covariant methods. e.g class Ret1{....} class B {     Ret1 foo(int n){       .......     } } class Ret2 extends Ret1{.....} class C extends B{      Ret2 foo(int n){         ....     } } In the derived class C, we are overriding the function foo. Return type of foo() in base class is Ret1 and return type of foo() in derived class is Ret2. This is valid because, Ret2 is a sub-class of Ret1. Let us look at a complete example. class Number { Number ( int n ) { this . n = n ; } int n ; } class SmallNumber extends Number { byte n ; SmallNumber ( byte n ) { super ( n );