Showing posts with label Conversion. Show all posts
Showing posts with label Conversion. Show all posts

How to convert String to Date in Java

We can convert String to Date in java using parse() method of DateFormat and SimpleDateFormat classes.

Approach: Using SimpleDateFormat

Java


import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class DateToString {
    public static void main(String[] argsthrows ParseException {
        String pattern = "MM/dd/yyyy HH:mm:ss";
        String strDate = "04/02/2021 22:57:29";
        SimpleDateFormat df = new SimpleDateFormat(pattern);

        Date today =df.parse(strDate);
        System.out.println("Today is: " + today);
    }
}

Output:


Today is: Fri Apr 02 22:57:29 IST 2021

How to convert Date to Timestamp in Java

We can convert Date to Timestamp in java using constructor of java.sql.Timestamp class.

Approach

Java



import java.sql.Timestamp;
import java.util.Date;

public class DateToTimestamp {
    public static void main(String[] args) {
        Date d = new Date();
        Timestamp ts = new Timestamp(d.getTime());
        System.out.println("Time stamp value " + d.getTime());
        System.out.println(ts);
    }
}


One Time Zone to Another Time Zone date converter in java

 The java.text.SimpleDateFormat class is used to both parse and format dates according to a formatting pattern you specify yourself


Approach :1 One Time Zone to Another Time Zone date converter


import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;

public class DateFormat {
    public static void main(String[] args) {

        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");

        sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
        System.out.println("UTC: " + sdf.format(calendar.getTime()));

        sdf.setTimeZone(TimeZone.getTimeZone("Europe/Paris"));
        System.out.println("Europe:  " + sdf.format(calendar.getTime()));

        sdf.setTimeZone(TimeZone.getTimeZone("Asia/Kolkata"));
        System.out.println("Indian: " + sdf.format(calendar.getTime()));
    }
}

SimpleDate Formatter Syntax 


y   Year (e.g12 or 2012). Use either yy or yyyy.
M   Month in yearNumber of M's determine length of format (e.g. MM, MMM or MMMMM)
d   Day in month. Number of d's determine length of format (e.gd or dd)
h   Hour of day, 1-12 (AM / PM) (normally hh)
H   Hour of day, 0-23 (normally HH)
m   Minute in hour, 0-59 (normally mm)
s   Second in minute, 0-59 (normally ss)
S   Millisecond in second, 0-999 (normally SSS)
E   Day in week (e.g Monday, Tuesday etc.)
D   Day in year (1-366)
F   Day of week in month (e.g1st Thursday of December)
w   Week in year (1-53)
W   Week in month (0-5)
a   AM / PM marker
k   Hour in day (1-24, unlike HH's 0-23)
K   Hour in day, AM / PM (0-11)
z   Time Zone

Example : 

Date Patter                 Example
dd-MM-yy                    30-03-21
dd-MM-yyyy                  30-02-2021
MM-dd-yyyy                  03-30-2021
yyyy-MM-dd                  2021-03-30
yyyy-MM-dd HH:mm:ss         2021-03-30 23:59:59
yyyy-MM-dd HH:mm:ss.SSS     2021-03-30 23:59:59.999
yyyy-MM-dd HH:mm:ss.SSSZ    2021-03-30 23:59:59.999+0100
EEEEE MMMMM yyyy HH:mm:ss.SSSZ  Tuesday March 2021 10:45:42.720+0100

Prime Number of Set Bits in Binary Representation

Given two integers L and R, find the count of numbers in the range [L, R] (inclusive) having a prime number of set bits in their binary representation.

Example:

Input: L = 6, R = 10
Output: 4
Explanation:
6 -> 110 (2 set bits, 2 is prime)
7 -> 111 (3 set bits, 3 is prime)
9 -> 1001 (2 set bits , 2 is prime)
10->1010 (2 set bits , 2 is prime)

Approach:

C++

#include <bits/stdc++.h>
using namespace std;

int countSetBits(int n)
{
    int cnt = 0;
    while (n > 0)
    {
        n = n & (n - 1);
        cnt++;
    }
    return cnt;
}
int countPrimeSetBits(int Lint R)
{

    bool prime[1000001];
    memset(primetruesizeof(prime));
    prime[0] = false;
    prime[1] = false;
    for (int i = 2i * i <= 1000000i++)
    {
        if (prime[i])
        {
            for (int j = i * ij <= 1000000j += i)
            {
                prime[j] = false;
            }
        }
    }
    int ans = 0;
    for (int i = Li <= Ri++)
    {
        int cnt = countSetBits(i);
        if (prime[cnt])
        {
            ans++;
        }
    }
    return ans;
}

int main()
{
    int L = 6R = 10;

    cout << countPrimeSetBits(LR);

    return 0;
}


Binary Number with Alternating Bits

Given a positive integer, check whether it has alternating bits: namely if two adjacent bits will always have different values.

Example :

Input: n = 5
Output: true
Explanation: The binary representation of 5 is: 101

Approach:

C++

#include <bits/stdc++.h>
using namespace std;

string toBinary(int n)
{
    string res = "";
    while (n > 0)
    {
        if (n % 2 == 0)
            res = '0' + res;
        else
            res = '1' + res;
        n = n / 2;
    }
    return res;
}
bool hasAlternatingBits(int n)
{
    string str = toBinary(n);
    int len = str.size();

    for (int i = 0i < len - 1i++)
    {
        if (str[i] == '0' && str[i + 1] == '0')
            return false;
        else if (str[i] == '1' && str[i + 1] == '1')
            return false;
    }
    return true;
}
int main()
{
    int n = 5;

    if (hasAlternatingBits(n))
        cout << "true";
    else
        cout << "false";

    return 0;
}


Binary Gap

Given a positive integer n, find and return the longest distance between any two adjacent 1's in the binary representation of n. If there are no two adjacent 1's, return 0.

Two 1's are adjacent if there are only 0's separating them (possibly no 0's). The distance between the two 1's is the absolute difference between their bit positions. For example, the two 1's in "1001" have a distance of 3.

Example :

Input: n = 22
Output: 2

Approach:

C++

#include <bits/stdc++.h>
using namespace std;

//convert number to binary string
string binary(int n)
{
    string res = "";
    while (n > 0)
    {
        int temp = n % 2;

        res = to_string(temp+ res;
        n = n / 2;
    }
    return res;
}
int binaryGap(int n)
{
    string bString = binary(n);

    int ans = 0;
    int len = bString.size();
    int i = 0;
    while (i < len)
    {
        int count = 0;
        while (i < len && bString[i] == '0')
        {
            i++;
        }
        int j = i;
        i++;
        while (i < len && bString[i] == '0')
        {
            i++;
        }
        if (i == len)
        {
            break;
        }
        else
        {
            ans = max(ansi - j);
        }
    }
    return ans;
}

int main()
{
    int n = 22;

    cout << binaryGap(n);

    return 0;
}


Complement of Base 10 Integer

Every non-negative integer N has a binary representation.  For example, 5 can be represented as "101" in binary, 11 as "1011" in binary, and so on.  Note that except for N = 0, there are no leading zeroes in any binary representation.

The complement of a binary representation is the number in binary you get when changing every 1 to a 0 and 0 to a 1.  For example, the complement of "101" in binary is "010" in binary.

For a given number N in base-10, return the complement of its binary representation as a base-10 integer.

    Example:

    Input: 5
    Output: 2
    Explanation: 5 is "101" in binary, with complement "010" in binary, which is 2 in base-10.
    

    Approach:

    C++

    #include <bits/stdc++.h>
    using namespace std;

    int bitwiseComplement(int N)
    {
        if (N == 0)
            return 1;
        vector<intarr;
        while (N > 0)
        {
            if (N % 2 == 0)
                arr.push_back(1);
            else
                arr.push_back(0);
            N = N / 2;
        }
        int res = 0;
        for (int i = 0i < arr.size(); i++)
        {
            res += arr[i] * pow(2i);
        }
        return res;
    }
    int main()
    {
        int n = 5;

        cout << bitwiseComplement(n);
        return 0;
    }


    Convert a Number to Hexadecimal

    Given an integer, write an algorithm to convert it to hexadecimal. For negative integers, two's complement method is used.

    Note:

    1.All letters in hexadecimal (a-f) must be in lowercase.

    2.The hexadecimal string must not contain extra leading 0. If the number is zero, it is represented by a single zero character '0'; otherwise, the first character in the hexadecimal string will not be the zero character.

    3.The given number is guaranteed to fit within the range of a 32-bit signed integer.

    4.You must not use any method provided by the library which converts/formats the number to hex directly.

    Example :

    Input:
    26
    
    Output:
    "1a"

    Approach:

    C++

    #include <bits/stdc++.h>
    using namespace std;

    string toHex(int num)
    {
        if (num == 0)
        {
            return "0";
        }

        unsigned int n = num;
        string res;
        char mp[16] = {'0''1''2''3''4''5''6''7',
                       '8''9''a''b''c''d''e''f'};

        while (n != 0)
        {
            res = mp[(n & 15)] + res;
            n >>= 4;
        }

        return res;
    }

    int main()
    {
        int n = 26;
        cout << toHex(n);

        return 0;
    }


    Base 7

    Given an integer, return its base 7 string representation.

    Example:

    Input: 100
    Output: "202"
    

    Approach:

    Java


    public class Base7 {
        public static void main(String[] args) {
            int num = 100;

            System.out.println(convertToBase7(num));
        }

        static String convertToBase7(int num) {
            String res = "";
            if (num == 0)
                return "0";
            int flag = 0;
            if (num < 0)
                flag = 1;
            num = Math.abs(num);
            while (num > 0) {
                int rem = num % 7;
                num = num / 7;
                res = rem + res;
            }
            if (flag != 0)
                res = "-" + res;

            return res;
        }
    }

    C++

    #include <bits/stdc++.h>
    using namespace std;

    string convertToBase7(int num)
    {
        string res = "";
        if (num == 0)
            return "0";
        int flag = 0;
        if (num < 0)
            flag = 1;
        num = abs(num);
        while (num > 0)
        {
            int rem = num % 7;
            num = num / 7;
            res += ('0' + rem);
        }
        if (flag)
            res += "-";
        reverse(res.begin(), res.end());
        return res;
    }

    int main()
    {
        int num = 100;

        cout << convertToBase7(num);

        return 0;
    }