To use recursion for solving excel file column number problem, the key idea is
to break down the number using base-26 logic. We reduce the problem by
continuously dividing the number by 26 and handling the remainder, which
corresponds to the last letter of the column label.
Recursive Code:
java
package
com.demo; public class
ExcelColumnNumber { // Recursive function to calculate Excel
column label public static String columnNumber(int
number) { if (number <= 0) { return ""; // Base
case: Invalid input (less than 1) } // Adjust to 0-based indexing for
correct remainder calculation number--; // Recursive case: process the next
character char letter = (char) (number % 26 +
'A'); int next = number / 26; // Recursively process the remaining
digits return columnNumber(next) + letter; } public static void main(String[] args) { // Test cases System.out.println("Excel file
column no -> " + columnNumber(90));
// Expected: "CR" System.out.println("Excel file
column no -> " + columnNumber(25));
// Expected: "Y" System.out.println("Excel file
column no -> " + columnNumber(255));
// Expected: "IV" System.out.println("Excel file
column no -> " + columnNumber(2700)); // Expected: "DVE" } } |
How the Recursion Works:
- Base
Case: If the number is 0 or negative, it is invalid, and the function
returns an empty string.
- Recursive
Case:
ü
We convert the number from 1-based indexing
(Excel format) to 0-based (which simplifies the math) by subtracting 1.
ü
The current column letter is derived by
computing number % 26 + 'A' (where number % 26 gives us the correct letter from
'A' to 'Z').
ü
We recursively process the next part of the
number by dividing it by 26.
- Combining
Results: At each step of recursion, the column letter is added to the
result, building the final string as the recursion unwinds.
Example Execution for columnNumber(90):
Ø 90
(in Excel numbering) corresponds to "CR".
1. columnNumber(90
- 1 = 89) → remainder is 17 ('R') and recursive call for 89 / 26 = 3.
2. columnNumber(3
- 1 = 2) → remainder is 2 ('C') and recursive call for 2 / 26 = 0.
3. columnNumber(0)
→ base case, returns "".
The results combine in reverse order, so you get "C"
+ "R" = "CR".
Sample Output:
Plain text
Excel file
column no -> CR Excel file
column no -> Y Excel file
column no -> IV Excel file
column no -> DVE |
This recursive approach properly handles the conversion of
numbers into Excel column labels. Let me know if you need further
clarifications or modifications!
0 Comments