Skip to main content

Featured

Solve LeetCode 3 Longest Substring Without Repeating Characters in C++ using the sliding window

Longest Substring Without Repeating Characters in C++ LeetCode 3 · sliding window · last index array Table of Contents Problem Statement Approach Algorithm C++ Program Input Sample Output Output Explanation Dry Run Flow of Execution Time Complexity Space Complexity Applications Key Points Interview Questions Frequently Asked Questions Conclusion Problem Statement 3. Longest Substring Without Repeating Characters Given a string s , find the length of the longest substring that contains no repeating characters. A substring is a continuous part of the string, so "pwke" is a subsequence of "pwwkew" but not a substring. Approach We use a sliding window . The window is the part of the string between start and end , and we always keep it free of repeated characters. An array lastIndex of size 128 remembers the most recent position of every ASCII ...

Reverse Number Using Recursion in C

C Program: Reverse Number Using Recursion

๐Ÿ”ท C Program: Reverse Number Using Recursion

#include<stdio.h>

int reverse(int num, int rev)
{
    if(num == 0)
    {
        return rev;
    }
    else
    {
        return reverse(num / 10, rev * 10 + num % 10);
    }
}

int main()
{
    int num, result;
    printf("Enter the number:\n");
    scanf("%d", &num);

    printf("Before Reversing: %d\n", num);

    if(num <= 0)
    {
        result = reverse(-num, 0);
        printf("After Reversing: -%d\n", result);
    }
    else
    {
        result = reverse(num, 0);
        printf("After Reversing: %d\n", result);
    }
}
  

๐Ÿ“˜ Explanation:

This C program uses a **recursive function** to reverse a given number.

๐Ÿ”ธ The `reverse()` function takes two arguments: - `num`: the original number (or part of it as recursion progresses)
- `rev`: the reversed number being constructed

๐Ÿ”ธ The base condition is when `num` becomes 0. At that point, the accumulated `rev` is returned.

๐Ÿ”ธ During each recursive call: - The last digit of `num` (`num % 10`) is added to `rev` after multiplying `rev` by 10 to shift its digits left.
- Then `num` is reduced by removing the last digit using integer division (`num / 10`).

๐Ÿ”ธ Special handling is added to work with **negative numbers** by reversing the absolute value and printing a minus sign manually.

๐Ÿ” Sample Output:

Enter the number:
1234
Before Reversing: 1234
After Reversing: 4321

Enter the number:
-786
Before Reversing: -786
After Reversing: -687

Enter the number:
0
Before Reversing: 0
After Reversing: 0
    

๐Ÿท️ Keywords:

C reverse number program, recursion in C, reverse using recursion, reverse number logic, C number manipulation, beginner recursion program

Comments

Popular Posts

๐ŸŒ™