c++ program Take any arbitrary number, n , and append zero (0) or more numeric d
ID: 3757421 • Letter: C
Question
c++ program
Take any arbitrary number, n, and append zero (0) or more numeric digits at the end of it to obtain a palindrome. The numeric palindrome should be the shortest possible. Return the integral length of your shortest possible palindrome (NOT your new palindrome) per given input, n. For any non-palindrome n, the function returns 0. You MUST make use of the following function signature:
Note: you may reuse the function from your lab as the helper utility to solve for the above:
Or, you may use any other subroutines, functions, methods, etc., you need to help you solve the getShortestLength() problem.
Examples:
input: 121
output: 3 // (because 121 is already a palindrome)
input: 12393
output: 7 // (because 12393 -> 1239321)
input: 123
output: 5 // (because 123 -> 12321)
input: -234
output: 0 // (because -234 is not a palindrome)
Constraints/Assumptions:
Your integral input is assumed to have been within the acceptable INT_MIN and INT_MAX range
The function returns 0 for all non-palindrome input
Your input can be either positive or negative
Negative number is not palindromic
0 is a palindrome, so is any single positive digit (2, 3, ... , 9)
Explanation / Answer
#include<iostream>
using namespace std;
bool isPallindrome(int n){
int N=n;
int len=0;
while(n>0){ //FINDING LENGTH OF NUMBER
len++;
n/=10;
}
String s=to_string(N);
for(int i=0, j=len-1; i<len/2;i++, j--){
if(s[i]!=s[j]) return false;//NOT PALLINDROME
}
return true;
}
int getShortestLength(int n){
int N=n;
int len=0;
while(n>0){ //FINDING LENGTH OF NUMBER
len++;
n/=10;
}
int L=len;
int K=N;
while(len>0){
if(N<0) return 0; //NEGATIVE NUMBER
if(isPallindrome(N)) return L; //CHECK NUMBER
N=N*10+K%10; //APPEND PREVOIUS DIGIT TO NUMBER
L++; //INCREASE LENGTH BY 1
K=K/10;
len--;
}
return L;
}
int main(){
int n;
cin>>n;
cout<<getShortestLength(n);
return 0;
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.