Convert given days to years, weeks and days

Write a program to convert given days to years, weeks and days.

Example 1:

Input: days=1320
Output: Years=3, Weeks=32, Days=1

Approach

Java

public class ConvertDaysToYYWWDD {
    public static void main(String[] args) {
        int days = 1320;
        int year = years(days);
        int week = weeks(days);
        int day = days(days);
        System.out.println("Years " + year);
        System.out.println("Weeks " + week);
        System.out.println("Days " + day);
    }

    private static int days(int days) {
        int year = days / 365;
        int rDays = (days - year * 365);
        int week = rDays / 7;
        rDays = (rDays - week * 7);
        return rDays;
    }

    private static int weeks(int days) {
        // Calculate years
        int year = days / 365;
        // remaining days after year
        int rDays = (days - year * 365);
        // remaining days after year and week
        int week = rDays / 7;
        return week;
    }

    private static int years(int days) {
        // calculate year's
        int year = days / 365;
        return year;
    }
}

C++

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

//function to find the years
int yearConvert(int days)
{
    //years 
    int year=days/365;
    return year;
}
int weekConvert(int days)
{
    int year=days/365;
    //remaning days after year
    int rDays=days-year*365;
    //calcuate weeks
    int week=rDays/7;
    return week;
}
int dayConvert(int days)
{
    int year=days/365;
    int rDays=days-year*365;
    int week=rDays/7;
    //remaing days after year and weeks
    rDays=rDays-week*7;
    return rDays;
}
int main()
{
    int days=1320;
    int year=yearConvert(days);
    int weeks=weekConvert(days);
    int day=dayConvert(days);
    cout<<"Years "<<year<<"\n";
    cout<<"Weeks "<<weeks<<"\n";
    cout<<"Days "<<day<<"\n";
    return 0;
}


No comments:

Post a Comment