Created
August 1, 2022 10:55
-
-
Save viraatmaurya/03f20b3e4d99687e53e146485a6aa196 to your computer and use it in GitHub Desktop.
Next smaller number with the same digits in C language - 4 kyu
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/*Doesn't work on 970*/ | |
#include <stdio.h> | |
#include <stdlib.h> | |
#include <string.h> | |
#include <assert.h> | |
unsigned long long int next_smaller_number(unsigned long long int number); | |
int main(int argc, char const *argv[]) | |
{ | |
unsigned long long int result = 0; | |
result = next_smaller_number(441); | |
assert(result == 414); | |
printf("Test Passed\n"); | |
return 0; | |
} | |
unsigned long long int next_smaller_number(unsigned long long int number) | |
{ | |
if (number < 10) | |
{ | |
return -1; | |
} | |
unsigned long long int result = 0; | |
char *numberString = malloc(sizeof(char) * 30); | |
sprintf(numberString, "%llu", number); | |
int length = strlen(numberString), position = length - 1; | |
for (int i = length - 1; i > 0; i--) | |
{ | |
if (numberString[i] < numberString[i - 1]) | |
{ | |
position = (i - 1); | |
break; | |
} | |
} | |
char temp = numberString[position]; | |
numberString[position] = numberString[position + 1]; | |
numberString[position + 1] = temp; | |
for (int i = position + 1; i < length + 2; i++) | |
{ | |
if (numberString[i] < numberString[i + 1]) | |
{ | |
char temp = numberString[i]; | |
numberString[i] = numberString[i + 1]; | |
numberString[i + 1] = temp; | |
} | |
} | |
if (numberString[0] == '0') | |
{ | |
return -1; | |
} | |
result = atoll(numberString); | |
return result; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment