Kotlin Language Features Related to Null Handling

Any software engineer with a Java background would find the null handling features in the Kotlin language interesting. Let's summarize this topic with some examples. Nullable types: In Kotlin, types are non-nullable by default. If you want a variable to be able to hold a null value, you need to explicitly declare its type as nullable using the Type? syntax. For example, String? denotes a nullable string, while String represents a non-nullable string. Safe calls (?.): Kotlin introduces the safe call operator (?.) for handling nullable types. It allows you to safely invoke a method or access a property on a nullable object. If the object is null, the expression returns null instead of throwing a NullPointerException. Example: data class Person(val name: String, val age: Int, val address: String?) fun main() {     // Create a person with a nullable address     val person1 = Person("John Doe", 25, "123 Main Street")     val person2 = Person("Jane Doe", 30,...

Using XOR operator in bit manipulation problems

Problem description from LeetCode:

Given an array of numbers nums, in which exactly two elements appear only once and all the other elements appear exactly twice. Find the two elements that appear only once.

Input: [1,2,1,3,2,5] 
Output: [3,5]

Solution:

If we apply XOR to all the elements, the result is the XOR of the lonely integers. The next step is finding the two integers that produce the XOR result. 
To do that, we can use this trick:
The set bits of A XOR B  gives us which bits are different in A and B
After finding the last different set bit, we can dissect the numbers from the input. 

Source Code:

class Solution {
    
   public static int[] singleNumber(int[] nums) {
        int xor = 0;
        for (int num : nums) {
            xor ^= num;
        }
        int lastSetBit = lastSetBit(xor);

        int set1 = 0; int set2 = 0;
        for (int i = 0; i < nums.length; ++i) {

            if ((nums[i] & lastSetBit) == 0) {
                set1 ^= nums[i];
            } else {
                set2 ^= nums[i];
            }
        }

        return new int[]{set1, set2};
    }

    private static int lastSetBit(int xor) {

        int i = 0;
        for (; i < 32; ++i) {
            if ((xor & (1 << i)) != 0) {
                break;
            }
        }

        return (1 << i);
    }
    
}


Comments

Popular posts from this blog

Trie Data Structure and Finding Patterns in a Collection of Words

Virtual Memory

NOTES ON COMPUTER ARCHITECTURE: Some important concepts in computer architecture