How do I change my code so that the numbers 1112, 2111, 1211 or 1121 work in this code to reach Kaprekar's Constant?
6 views (last 30 days)
Show older comments
I think my code doesn't account for leading zeros. Is there a way to modify a certain part for it to include a leading zero? Thanks!
clear
clc
constant = 6174; % Initialize Kaprekar's constant for the while loop
steps = 0; % Initialize steps in the while loop counter
stop = 0; % Initialize the condition of the while loop
% User inputs a number and then checks if the user input number is four digits and contains at least two distinct digits
input = input('Please enter a 4 digit number: ', 's');
if numel(input) < 4 || length(unique(input)) < 2 || ~all(isstrprop(input, 'digit'))
disp("Error. Not a valid number. Enter a four digit number with at least two distinct numbers.");
end
disp("Below are the steps required for your input number to get to Kaprekar's Constant: ")
while stop < 1
descending = sort(num2str(input), 'descend');
ascending = sort(num2str(input)); % Arranges the user input number in descending and ascending order as a string
highnumber = str2num(descending);
lownumber = str2num(ascending); % Converts the string back to a integer number to be used in the following calculation
input = highnumber - lownumber; % Subtracts the two numbers and records it as 1 step
steps = steps + 1;
fprintf('Step %d: %d - %d = %d. \n', steps, highnumber, lownumber, input) % Shows each step of the calculation to reach Kaprekar's Constant.
if input == constant
stop = 3; % If this if statement is satisifed, the while loop ends
end
end
disp("Kaprekar's Constant has been reached! Amount of steps required: " + steps)
0 Comments
Accepted Answer
John D'Errico
on 26 Feb 2024
Edited: John D'Errico
on 26 Feb 2024
Numbers in MATLAB do not have leading zeros. Sorry. That is not a valid number, just a string of numeric digits.
If you need leading zero digits, then work with vectors of digits. For example [0 0 1 1 2 1]. Or you can work with actual strings, like "001121". But then the elements in the string are not even digits. That forces you to do an extra step when you want to do any computations.
Anyway, since you are converting back and forth between actual numbers and strings, that means you will best just work with a vector of digits.
0 Comments
More Answers (0)
See Also
Categories
Find more on Numeric Types in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!